Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 707
Old Geezer Avatar asked Mar 23 '17 10:03

Old Geezer


People also ask

Which method of fs module is used to read a directory?

The fs. readdir() method is used to asynchronously read the contents of a given directory. The callback of this method returns an array of all the file names in the directory.

What is fs module used for?

js file system module helps us store, access, and manage data on our operating system. Commonly used features of the fs module include fs. readFile to read data from a file, fs. writeFile to write data to a file and replace the file if it already exists, fs.

Which method of fs module is used to remove a directory?

The fs. rmdir() method is used to delete a directory at the given path.


1 Answers

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

like image 64
ardilgulez Avatar answered Sep 18 '22 15:09

ardilgulez