简体   繁体   English

在 NODE.JS 中使用路径模块

[英]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.我试图将文件的绝对路径存储在变量中,通过 module.exports 将其导出以在其他文件中使用它,例如,另一个项目文件夹中的文件,通过 require 访问它。 After that, I use this variable as the path of the readFileSync method.之后,我使用这个变量作为 readFileSync 方法的路径。 Very well, when running the code in VS Code, it works perfectly, but when I try to run it in the terminal, the path that appears is different?很好,在 VS Code 中运行代码时,它完美运行,但是当我尝试在终端中运行它时,出现的路径不同? 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.当我在 VS 中运行时。 Code, the content of test.txt is visible.代码,test.txt的内容是可见的。 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.当我在 fs 文件夹中运行时,它会将此文件夹识别为路径的一部分。

It looks like you're trying to make an path relative to the source file.看起来您正在尝试创建相对于源文件的路径。

To do this, add __dirname to the start:为此,将 __dirname 添加到开头:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM