Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relative file system write path within module

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?

like image 484
ThomasReggi Avatar asked Mar 06 '13 18:03

ThomasReggi


People also ask

How do I give a relative a file path in Python?

relpath() method in Python is used to get a relative filepath to the given path either from the current working directory or from the given directory. Note: This method only computes the relative path. The existence of the given path or directory is not checked.

How do I add a relative file path?

To set this option, look under the File menu and click Map Document Properties. Here, you can specify whether to store absolute or relative paths.


1 Answers

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.

like image 87
David Weldon Avatar answered Oct 14 '22 08:10

David Weldon