These quick tips are small snippets that come up again and again in my work, for which I want a permantent and central place to retrieve them.
Here's the situation: You want your node script to interact with a file that is relative to its location. To do that, you need a way to determine that location.
To get the absolute path to a module, you can use the global
For the follwing snippets, suppose you run the module
// this will print '/home/urname/code/script' console.log(__dirname)
If you want the filename included as well,
__filename will do the trick.
// this will print '/home/urname/code/script/main.js' console.log(__filename)
Get the current working directory
Since it fits the topic somewhat, here's a small bonus: If you want to get the directory from which you called the script, you can use
process.cwd() to do that.
Suppose you call
/home/urname/code/script/main.js from the command line while you are inside
// this will print '/home/urname/code/temp' console.log(process.cwd())
Get the directory of the main script
Finally, if you write a plug-in and need to know the path of the main script, you can use
Top comments (0)