javascript process.env.PWD 与 process.cwd()

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

process.env.PWD vs process.cwd()

javascriptnode.jsmeteorfs

提问by preston

I am using Meteor JS...and within my Meteor app I am using node to query the contents of different directories within the app....

我正在使用 Meteor JS...并且在我的 Meteor 应用程序中我使用 node 来查询应用程序中不同目录的内容....

When I use process.env.PWDto query the contents of a folder I get a different result from when I use process.cwd()to query the results of a folder.

当我process.env.PWD用来查询文件夹的内容时,我得到的结果与process.cwd()用来查询文件夹结果时的结果不同。

var dirServer = process.env.PWD + '/server/';
var dirServerFiles = fs.readdirSync(dirServer);
console.log(dirServerFiles); 
//outputs: [ 'ephe', 'fixstars.cat', 'sepl_30.se1', 'server.js' ]

vs

对比

var serverFolderFilesDir = process.cwd() +"/app/server";
var serverFolderFiles = fs.readdirSync(serverFolderFilesDir);
console.log(serverFolderFiles); 
//outputs: [ 'server.js' ]

using process.cwd()only shows server.jswithin the Meteor.

process.cwd()仅使用server.jsMeteor 中的节目。

Why is this? How is process.cwd()different from process.env.PWD?

为什么是这样?如何process.cwd()不同process.env.PWD

回答by tadman

They're related but not the same thing.

它们是相关的,但不是一回事。

process.env.PWDis the working directory when the process was started. This stays the same for the entire process.

process.env.PWD进程启动时的工作目录。这在整个过程中保持不变。

process.cwd()is the currentworking directory. It reflects changes made via process.chdir().

process.cwd()当前工作目录。它反映了通过process.chdir().

It's possible to manipulate PWDbut doing so would be meaningless, that variable isn't used by anything, it's just there for convenience.

可以进行操作,PWD但这样做毫无意义,该变量不会被任何东西使用,它只是为了方便而存在。

For computing paths you probably want to do it this way:

对于计算路径,您可能希望这样做:

var path = require('path');
path.resolve(__dirname, 'app/server')

Where __dirnamereflects the directory the source file this code is defined in resides. It's wrong to expect that cwd()will be anywhere near that. If your server process is launched from anywhere but the main source directory all your paths will be incorrect using cwd().

哪里__dirname反映了定义此代码的源文件所在的目录。期望它cwd()会接近那个是错误的。如果您的服务器进程是从主源目录以外的任何地方启动的,那么使用cwd().