process.env.PWD vs process.cwd()

依然范特西╮ 提交于 2019-12-07 00:44:12

问题


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

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.

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.

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


回答1:


They're related but not the same thing.

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

process.cwd() is the current working directory. It reflects changes made via 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.

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. 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().



来源:https://stackoverflow.com/questions/31414852/process-env-pwd-vs-process-cwd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!