Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node get path of the requiring parent file

Tags:

node.js

I'm writing a node module and need to read a file in the same directory as the file which requires my module.

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

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

like image 959
alt Avatar asked Nov 29 '13 19:11

alt


1 Answers

Inside your file you will have a module global (not actually a global) you can get the parent object using module.parent and the filename with module.parent.filename then you could extract the folder

so from 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 of the file which was executed then you can use require.main.filename

like image 168
Diadara Avatar answered Nov 15 '22 20:11

Diadara