What is the current directory used by fs module functions?

40,469

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

Share:
40,469
Old Geezer
Author by

Old Geezer

Don't shoot the messenger. An expert, or teacher, is a person who, after reading your question, knows what you know, what you don't know, what you are trying to know, and what else you need to know in order to achieve what you are trying to know.

Updated on July 09, 2022

Comments

  • Old Geezer
    Old Geezer almost 2 years

    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/

  • robertklep
    robertklep over 7 years
    It's not the directory where the script is located, it's the directory where the node interpreter was started from (aka the current working directory).
  • Old Geezer
    Old Geezer over 7 years
    @ardilgulez I have expanded my question with my experience.