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