node.js 模块内的相对文件系统写入路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15254861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 13:46:22  来源:igfitidea点击:

Relative file system write path within module

node.jspathrelative-pathfs

提问by ThomasReggi

I have a executable node / javascript script that has a debug boolean, if set to true a couple of files will be written. This executable is also node module. Depending on the working directory of the user running the script it seems that the function can't find the directory to write files into.

我有一个具有调试布尔值的可执行节点/javascript 脚本,如果设置为 true,将写入几个文件。这个可执行文件也是节点模块。根据运行脚本的用户的工作目录,该函数似乎找不到要将文件写入的目录。

The module is structured like this

该模块的结构如下

output/
lib/
    helpers.js
index.js

My original reasoning would be to have the path be.

我最初的推理是让路径成为。

helper.write = function(data,filename){
    if(typeof data !== "string") data = JSON.stringify(data);
    fs.writeFileSync("./output/"+filename, data);
};

However this works when running the script from within the node_module folder

但是,这在从 node_module 文件夹中运行脚本时有效

fs.writeFileSync("process.cwd()+"/node_modules/the_module/output/"+filename, data);

Like this

像这样

node ./my_app/node_modules/the_module/index.js

This gets even more confusing if the modules is used in another executable file that uses the library.

如果在另一个使用该库的可执行文件中使用这些模块,这会变得更加混乱。

node ./my_app/run.js

Is there a way to save the file independent from all of these variables?

有没有办法独立于所有这些变量保存文件?

回答by David Weldon

If I understand the question correctly, you want to always write to a path relative to the current script. To get the name of the directory that the currently executing script resides in, you can use __dirnamelike so:

如果我正确理解了这个问题,您希望始终写入相对于当前脚本的路径。要获取当前正在执行的脚本所在目录的名称,您可以__dirname像这样使用:

var path = require('path');

helper.write = function(data,filename){
  if(typeof data !== "string") data = JSON.stringify(data);
  var file = path.join(__dirname, 'output', filename);
  fs.writeFileSync(file, data);
};

That being said, I don't think it's good practice to be writing files inside of your node_modulesdirectory. I'd recommend that your module require the full path to a file somewhere else in the file system. If the caller wishes to write to an output directory in its own project tree, you can again use the same __dirnametrick.

话虽如此,我认为在node_modules目录中写入文件并不是一个好习惯。我建议您的模块需要文件系统中其他位置的文件的完整路径。如果调用者希望写入自己项目树中的输出目录,您可以再次使用相同的__dirname技巧。