Node get the path to the required parent file

I am writing a node module and should read the file in the same directory as the file that my module requires.

For example, I have app.js and in the same template.html folder. In some unknown directory module.js and app.js require it.

How can I read template.html from module.js ?

+7
source share
3 answers

Inside your file you will have a global module (not a global one), you can get the parent using module.parent and the file name using module.parent.filename , then you can extract the folder

so from your module.js you can use module.parent.filename. http://nodejs.org/api/modules.html

 p = require('path') template = p.join(p.dirname(module.parent.filename),'template.html') 

And if you are looking for the path to the file that was executed, you can use require.main.filename

+16
source share

Have a look here: http://nodejs.org/docs/latest/api/globals.html#globals_dirname

You can simply do this from app.js :

 var path = __dirname + '/template.html'; 

Then you can send this path to your module.js via some function or API.

Then your module can simply use this path.

0
source share

Inside the "module.js" trick uses module.parent. filename

I personally do not like to use global variables, and for certain files (for example, configuration or templates), managing the module requires that the stack be not so difficult.

module.parent maps to the parent module (which may be app.js, as in your example).

By combining module.parent.filename with a path module, you get a few useful things, such as:

  var path = require('path'); var parent_path = path.dirname(module.parent.filename); var parent_relative = path.resolve(path.join(parent_path, '../', 'view')); var template = path.join(parent_path,'./views/template.html'); 

I don't like using global variables for anything related to paths, I get spagetti ../../../dir./s

0
source share

All Articles