What is the current directory used by fs module functions?

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

 var fs = require('fs'); var data = fs.readFile("abc.jpg", "binary"); 

What is the default folder used to search for abc.jpg? Is it dependent on the contents of the script folder?

Is there a way to query the current directory?


My file structure:

 ExpressApp1/ app.js routes/ members.js 

In members.js, I have fs.createWriteStream("abc") , and the abc file was created in ExpressApp1/

+7
express fs
source share
1 answer

This is the directory where the node interpreter was run (or the current working directory), and not the script folder location directory (thanks robertklep).

In addition, the current working directory can be obtained:

 process.cwd() 

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

EDIT: since you started app.js via node app.js in the ExpressApp1 directory, each relative path will refer to the ExpressApp1 folder, so fs.createWriteStream("abc") will create a write stream to write to the 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")); 

More details:

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

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

+11
source share

All Articles