简体   繁体   English

process.env.PWD 与 process.cwd()

[英]process.env.PWD vs process.cwd()

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.PWD to 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.js within the Meteor.使用process.cwd()只在 Meteor 中显示server.js

Why is this?为什么是这样? How is process.cwd() different from process.env.PWD ? process.cwd()process.env.PWD有何不同?

They're related but not the same thing.它们是相关的,但不是一回事。

process.env.PWD is the working directory when the process was started . process.env.PWD进程启动时的工作目录。 This stays the same for the entire process.这在整个过程中保持不变。

process.cwd() is the current working directory. process.cwd()当前工作目录。 It reflects changes made via process.chdir() .它反映了通过process.chdir()所做的更改。

It's possible to manipulate PWD but 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 __dirname reflects the directory the source file this code is defined in resides.其中__dirname反映了定义此代码的源文件所在的目录。 It's wrong to expect that cwd() will be anywhere near that.期望cwd()会接近该值是错误的。 If your server process is launched from anywhere but the main source directory all your paths will be incorrect using cwd() .如果您的服务器进程是从主源目录以外的任何地方启动的,则使用cwd()所有路径都将不正确。

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

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