u936293
u936293

Reputation: 16244

What is the current directory used by fs module functions?

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

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?

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 abc was created in ExpressApp1/

Upvotes: 49

Views: 52041

Answers (1)

ardilgulez
ardilgulez

Reputation: 1944

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

Also, current working directory can be obtained by:

process.cwd()

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

EDIT: Because you started app.js by node app.js at ExpressApp1 directory, 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.js to:

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

For more:

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

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

Upvotes: 77

Related Questions