Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

183
Views
Using Path Module in NODE.JS

I'm trying to store the absolute path of a file in a variable, exporting it through module.exports to use it in other files, for example, a file in another project folder, accessing it by require. After that, I use this variable as the path of the readFileSync method. Very well, when running the code in V.S Code, it works perfectly, but when I try to run it in the terminal, the path that appears is different! Why does it happen?

//path_module.js file code (located in 'path' folder):

const testPath = path.resolve('path','content', 'subfolder', 'test.txt');
console.log(testPath);

module.exports = testPath;

//fileSync_modules.js file code (located in 'fs' folder):

const fs = require('fs');

const testPath = require('../path/path_module')

const readFile = fs.readFileSync(testPath, 'utf8');
console.log(readFile);

When I run in VS. Code, the content of test.txt is visible. When I run in terminal, it gives a path error:

Error: ENOENT: no such file or directory, open 'C:\\Users\\home\\alvaro\\node\\fs\\path\\content\\subfolder\\test.txt'

As I'm running inside fs folder, it recognizes this folder as part of the path.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

It looks like you're trying to make an path relative to the source file.

To do this, add __dirname to the start:

const testPath = path.resolve(__dirname, 'path','content', 'subfolder', 'test.txt');
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!