node.js fs 模块函数使用的当前目录是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42972785/
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 18:06:36  来源:igfitidea点击:

What is the current directory used by fs module functions?

node.jsexpressfs

提问by Old Geezer

What is the current directory when a method in the fsmodule is invoked in a typical node.js/Express app? For example:

fs在典型的 node.js/Express 应用程序中调用模块中的方法时,当前目录是什么?例如:

var fs = require('fs');
var data = fs.readFile("abc.jpg", "binary");

What is the default folder used to locate abc.jpg? Is it dependent on the containing script's folder location?

用于定位 abc.jpg 的默认文件夹是什么?它是否取决于包含脚本的文件夹位置?

Is there a method to query the current directory?

有没有查询当前目录的方法?



My file structure is:

我的文件结构是:

ExpressApp1/
           app.js
           routes/
                 members.js

In members.js I have a fs.createWriteStream("abc")and file abcwas created in ExpressApp1/

在 members.js 我有一个fs.createWriteStream("abc")文件abc是在ExpressApp1/

回答by ardilgulez

It's the directory where the node interpreter was started from (aka the current working directory), not the directory of script's folder location (thank you robertklep).

它是节点解释器启动的目录(也称为当前工作目录),而不是脚本文件夹位置的目录(谢谢 robertklep)。

Also, current working directory can be obtained by:

此外,可以通过以下方式获取当前工作目录:

process.cwd()

For more information, you can check out: https://nodejs.org/api/fs.html

有关更多信息,您可以查看:https: //nodejs.org/api/fs.html

EDIT: Because you started app.js by node app.jsat ExpressApp1directory, every relative path will be relative to "ExpressApp1" folder, that's why fs.createWriteStream("abc")will create a write stream to write to a file in ExpressApp1/abc. If you want to write to ExpressApp1/routes/abc, you can change the code in members.jsto:

编辑:因为您通过node app.jsatExpressApp1目录启动 app.js ,所以每个相对路径都将相对于“ExpressApp1”文件夹,这就是为什么fs.createWriteStream("abc")要创建写入流以写入ExpressApp1/abc. 如果要写入ExpressApp1/routes/abc,可以将代码更改members.js为:

fs.createWriteStream(path.join(__dirname, "abc"));

For more:

更多信息:

https://nodejs.org/docs/latest/api/globals.html#globals_dirname

https://nodejs.org/docs/latest/api/globals.html#globals_dirname

https://nodejs.org/docs/latest/api/path.html#path_path_join_paths

https://nodejs.org/docs/latest/api/path.html#path_path_join_paths