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/
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.
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.
The fs. rmdir() method is used to delete a directory at the given path.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With