Relative file system write path within module

ThomasReggi picture ThomasReggi · Mar 6, 2013 · Viewed 27.7k times · Source

I have a executable node / javascript script that has a debug boolean, if set to true a couple of files will be written. This executable is also node module. Depending on the working directory of the user running the script it seems that the function can't find the directory to write files into.

The module is structured like this

output/
lib/
    helpers.js
index.js

My original reasoning would be to have the path be.

helper.write = function(data,filename){
    if(typeof data !== "string") data = JSON.stringify(data);
    fs.writeFileSync("./output/"+filename, data);
};

However this works when running the script from within the node_module folder

fs.writeFileSync("process.cwd()+"/node_modules/the_module/output/"+filename, data);

Like this

node ./my_app/node_modules/the_module/index.js

This gets even more confusing if the modules is used in another executable file that uses the library.

node ./my_app/run.js

Is there a way to save the file independent from all of these variables?

Answer

David Weldon picture David Weldon · Mar 6, 2013

If I understand the question correctly, you want to always write to a path relative to the current script. To get the name of the directory that the currently executing script resides in, you can use __dirname like so:

var path = require('path');

helper.write = function(data,filename){
  if(typeof data !== "string") data = JSON.stringify(data);
  var file = path.join(__dirname, 'output', filename);
  fs.writeFileSync(file, data);
};

That being said, I don't think it's good practice to be writing files inside of your node_modules directory. I'd recommend that your module require the full path to a file somewhere else in the file system. If the caller wishes to write to an output directory in its own project tree, you can again use the same __dirname trick.