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.
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');