How do I get the path to the current script with Node.js?
How would I get the path to the script in Node.js?
I know there's process.cwd
, but that only refers to the directory where the script was called, not of the script itself. For instance, say I'm in /home/kyle/
and I run the following command:
node /home/kyle/some/dir/file.js
If I call process.cwd()
, I get /home/kyle/
, not /home/kyle/some/dir/
. Is there a way to get that directory?
node.js
add a comment |
How would I get the path to the script in Node.js?
I know there's process.cwd
, but that only refers to the directory where the script was called, not of the script itself. For instance, say I'm in /home/kyle/
and I run the following command:
node /home/kyle/some/dir/file.js
If I call process.cwd()
, I get /home/kyle/
, not /home/kyle/some/dir/
. Is there a way to get that directory?
node.js
4
nodejs.org/docs/latest/api/globals.html the documentation link of the accepted answer.
– allenhwkim
Apr 12 '13 at 15:41
add a comment |
How would I get the path to the script in Node.js?
I know there's process.cwd
, but that only refers to the directory where the script was called, not of the script itself. For instance, say I'm in /home/kyle/
and I run the following command:
node /home/kyle/some/dir/file.js
If I call process.cwd()
, I get /home/kyle/
, not /home/kyle/some/dir/
. Is there a way to get that directory?
node.js
How would I get the path to the script in Node.js?
I know there's process.cwd
, but that only refers to the directory where the script was called, not of the script itself. For instance, say I'm in /home/kyle/
and I run the following command:
node /home/kyle/some/dir/file.js
If I call process.cwd()
, I get /home/kyle/
, not /home/kyle/some/dir/
. Is there a way to get that directory?
node.js
node.js
edited Dec 17 '16 at 12:03
Peter Mortensen
13.5k1983111
13.5k1983111
asked Jun 28 '10 at 14:31
Kyle Slattery
16.7k82635
16.7k82635
4
nodejs.org/docs/latest/api/globals.html the documentation link of the accepted answer.
– allenhwkim
Apr 12 '13 at 15:41
add a comment |
4
nodejs.org/docs/latest/api/globals.html the documentation link of the accepted answer.
– allenhwkim
Apr 12 '13 at 15:41
4
4
nodejs.org/docs/latest/api/globals.html the documentation link of the accepted answer.
– allenhwkim
Apr 12 '13 at 15:41
nodejs.org/docs/latest/api/globals.html the documentation link of the accepted answer.
– allenhwkim
Apr 12 '13 at 15:41
add a comment |
13 Answers
13
active
oldest
votes
I found it after looking through the documentation again. What I was looking for were the __filename
and __dirname
module-level variables.
__filename
is the file name of the current module. This is the resolved absolute path of the current module file. (ex:/home/kyle/some/dir/file.js
)
__dirname
is the directory name of the current module. (ex:/home/kyle/some/dir
)
3
If you want only the directory name and not the full path, you might do something like this: function getCurrentDirectoryName() { var fullPath = __dirname; var path = fullPath.split('/'); var cwd = path[path.length-1]; return cwd; }
– Anthony Martin
Oct 30 '13 at 20:34
51
@AnthonyMartin __dirname.split("/").pop()
– Kenan Sulayman
Mar 30 '14 at 20:13
5
For those trying @apx solution (like I did:), this solution does not work on Windows.
– Laoujin
May 7 '15 at 19:33
29
Or simply__dirname.split(path.sep).pop()
– Burgi
Jun 11 '15 at 10:53
38
Orrequire('path').basename(__dirname);
– Vyacheslav Cotruta
Oct 5 '15 at 9:03
|
show 5 more comments
So basically you can do this:
fs.readFile(path.resolve(__dirname, 'settings.json'), 'UTF-8', callback);
Use resolve() instead of concatenating with '/' or '' else you will run into cross-platform issues.
Note: __dirname is the local path of the module or included script. If you are writing a plugin which needs to know the path of the main script it is:
require.main.filename
or, to just get the folder name:
require('path').dirname(require.main.filename)
12
If your goal is just to parse and interact with the json file, you can often do this more easily viavar settings = require('./settings.json')
. Of course, it's synchronous fs IO, so don't do it at run-time, but at startup time it's fine, and once it's loaded, it'll be cached.
– isaacs
May 9 '12 at 18:26
2
@Marc Thanks! For a while now I was hacking my way around the fact that __dirname is local to each module. I have a nested structure in my library and need to know in several places the root of my app. Glad I know how to do this now :D
– Thijs Koerselman
Feb 28 '13 at 14:34
Node V8: path.dirname(process.mainModule.filename)
– wayofthefuture
Aug 26 '17 at 11:47
add a comment |
This command returns the current directory:
var currentPath = process.cwd();
For example, to use the path to read the file:
var fs = require('fs');
fs.readFile(process.cwd() + "\text.txt", function(err, data)
{
if(err)
console.log(err)
else
console.log(data.toString());
});
For those who didn't understand Asynchronous and Synchronous, see this link... stackoverflow.com/a/748235/5287072
– DarckBlezzer
Feb 3 '17 at 17:33
5
this is exactly what the OP doesn't want... the request is for the path of the executable script!
– caesarsol
Mar 29 '18 at 9:10
Current directory is a very different thing. If you run something likecd /foo; node bar/test.js
, current directory would be/foo
, but the script is located in/foo/bar/test.js
.
– rjmunro
Jul 5 '18 at 11:20
add a comment |
Use __dirname!!
__dirname
The directory name of the current module. This the same as the path.dirname() of the __filename
.
Example: running node example.js from /Users/mjr
console.log(__dirname);
// Prints: /Users/mjr
console.log(path.dirname(__filename));
// Prints: /Users/mjr
https://nodejs.org/api/modules.html#modules_dirname
1
This survives symlinks too. So if you create a bin and need to find a file, eg path.join(__dirname, "../example.json"); it will still work when your binary is linked in node_modules/.bin
– Jason
Apr 17 '18 at 17:12
add a comment |
When it comes to the main script it's as simple as:
process.argv[1]
From the Node.js documentation:
process.argv
An array containing the command line arguments. The first element will be 'node', the second element will be the path to the JavaScript file. The next elements will be any additional command line arguments.
If you need to know the path of a module file then use __filename.
3
Could the downvoter please explain why this is not recommended?
– Tamlyn
Jan 15 '16 at 16:57
1
@Tamlyn Maybe becauseprocess.argv[1]
applies only to the main script while__filename
points to the module file being executed. I update my answer to emphasize the difference. Still, I see nothing wrong in usingprocess.argv[1]
. Depends on one's requirements.
– Lukasz Wiktor
Jan 16 '16 at 6:40
1
@Tamlyn Not good when you think about testing.
– Karl Morrison
Sep 23 '16 at 8:56
7
If main script was launched with a node process manager like pm2 process.argv[1] will point to the executable of the process manager /usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js
– user3002996
Mar 1 '17 at 11:28
add a comment |
var settings =
JSON.parse(
require('fs').readFileSync(
require('path').resolve(
__dirname,
'settings.json'),
'utf8'));
7
Just a note, as of node 0.5 you can just require a JSON file. Of course that wouldn't answer the question.
– Kevin Cox
Apr 9 '13 at 21:18
add a comment |
Every Node.js program has some global variables in its environment, which represents some information about your process and one of it is __dirname
.
add a comment |
You can use process.env.PWD to get the current app folder path.
1
OP asks for the requested "path to the script". PWD, which stands for something like Process Working Directory, is not that. Also, the "current app" phrasing is misleading.
– dmcontador
Sep 8 '17 at 6:48
add a comment |
I know this is pretty old, and the original question I was responding to is marked as duplicate and directed here, but I ran into an issue trying to get jasmine-reporters to work and didn't like the idea that I had to downgrade in order for it to work. I found out that jasmine-reporters wasn't resolving the savePath correctly and was actually putting the reports folder output in jasmine-reporters directory instead of the root directory of where I ran gulp. In order to make this work correctly I ended up using process.env.INIT_CWD to get the initial Current Working Directory which should be the directory where you ran gulp. Hope this helps someone.
var reporters = require('jasmine-reporters');
var junitReporter = new reporters.JUnitXmlReporter({
savePath: process.env.INIT_CWD + '/report/e2e/',
consolidateAll: true,
captureStdout: true
});
god bless you, this is what I was looking for! you are my source of pure awesomeness for this day!
– YangombiUmpakati
Nov 16 '18 at 11:09
add a comment |
Node.js 10 supports ECMAScript modules, where __dirname
and __filename
are not available out of the box.
Then to get the path to the current ES module one has to use:
const __filename = new URL(import.meta.url).pathname;
And for the directory containing the current module:
import path from 'path';
const __dirname = path.dirname(new URL(import.meta.url).pathname);
add a comment |
If you are using pkg
to package your app, you'll find useful this expression:
appDirectory = require('path').dirname(process.pkg ? process.execPath : (require.main ? require.main.filename : process.argv[0]));
process.pkg
tells if the app has been packaged bypkg
.process.execPath
holds the full path of the executable, which is/usr/bin/node
or similar for direct invocations of scripts (node test.js
), or the packaged app.require.main.filename
holds the full path of the main script, but it's empty when Node runs in interactive mode.__dirname
holds the full path of the current script, so I'm not using it (although it may be what OP asks; then better useappDirectory = process.pkg ? require('path').dirname(process.execPath) : (__dirname || require('path').dirname(process.argv[0]));
noting that in interactive mode__dirname
is empty.For interactive mode, use either
process.argv[0]
to get the path to the Node executable orprocess.cwd()
to get the current directory.
Exactly what I was looking for, thanks.
– James Bruckner
Aug 18 '18 at 18:37
add a comment |
If you want something more like $0 in a shell script, try this:
var path = require('path');
var command = getCurrentScriptPath();
console.log(`Usage: ${command} <foo> <bar>`);
function getCurrentScriptPath () {
// Relative path from current working directory to the location of this script
var pathToScript = path.relative(process.cwd(), __filename);
// Check if current working dir is the same as the script
if (process.cwd() === __dirname) {
// E.g. "./foobar.js"
return '.' + path.sep + pathToScript;
} else {
// E.g. "foo/bar/baz.js"
return pathToScript;
}
}
add a comment |
Another approach, if you're using modules and you'd like to find the filename of the main module that called such sub-module or any module you're running, is to use
var fnArr = (process.mainModule.filename).split('/');
var filename = fnArr[fnArr.length -1];
2
NEVER usesplit
for directories! usepath.dirname
!
– caesarsol
Mar 29 '18 at 9:06
1
@caesarsol good point! Thank you
– João Pimentel Ferreira
Mar 29 '18 at 17:07
add a comment |
protected by eyllanesc Aug 14 '18 at 18:56
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
13 Answers
13
active
oldest
votes
13 Answers
13
active
oldest
votes
active
oldest
votes
active
oldest
votes
I found it after looking through the documentation again. What I was looking for were the __filename
and __dirname
module-level variables.
__filename
is the file name of the current module. This is the resolved absolute path of the current module file. (ex:/home/kyle/some/dir/file.js
)
__dirname
is the directory name of the current module. (ex:/home/kyle/some/dir
)
3
If you want only the directory name and not the full path, you might do something like this: function getCurrentDirectoryName() { var fullPath = __dirname; var path = fullPath.split('/'); var cwd = path[path.length-1]; return cwd; }
– Anthony Martin
Oct 30 '13 at 20:34
51
@AnthonyMartin __dirname.split("/").pop()
– Kenan Sulayman
Mar 30 '14 at 20:13
5
For those trying @apx solution (like I did:), this solution does not work on Windows.
– Laoujin
May 7 '15 at 19:33
29
Or simply__dirname.split(path.sep).pop()
– Burgi
Jun 11 '15 at 10:53
38
Orrequire('path').basename(__dirname);
– Vyacheslav Cotruta
Oct 5 '15 at 9:03
|
show 5 more comments
I found it after looking through the documentation again. What I was looking for were the __filename
and __dirname
module-level variables.
__filename
is the file name of the current module. This is the resolved absolute path of the current module file. (ex:/home/kyle/some/dir/file.js
)
__dirname
is the directory name of the current module. (ex:/home/kyle/some/dir
)
3
If you want only the directory name and not the full path, you might do something like this: function getCurrentDirectoryName() { var fullPath = __dirname; var path = fullPath.split('/'); var cwd = path[path.length-1]; return cwd; }
– Anthony Martin
Oct 30 '13 at 20:34
51
@AnthonyMartin __dirname.split("/").pop()
– Kenan Sulayman
Mar 30 '14 at 20:13
5
For those trying @apx solution (like I did:), this solution does not work on Windows.
– Laoujin
May 7 '15 at 19:33
29
Or simply__dirname.split(path.sep).pop()
– Burgi
Jun 11 '15 at 10:53
38
Orrequire('path').basename(__dirname);
– Vyacheslav Cotruta
Oct 5 '15 at 9:03
|
show 5 more comments
I found it after looking through the documentation again. What I was looking for were the __filename
and __dirname
module-level variables.
__filename
is the file name of the current module. This is the resolved absolute path of the current module file. (ex:/home/kyle/some/dir/file.js
)
__dirname
is the directory name of the current module. (ex:/home/kyle/some/dir
)
I found it after looking through the documentation again. What I was looking for were the __filename
and __dirname
module-level variables.
__filename
is the file name of the current module. This is the resolved absolute path of the current module file. (ex:/home/kyle/some/dir/file.js
)
__dirname
is the directory name of the current module. (ex:/home/kyle/some/dir
)
edited Oct 24 '18 at 15:40
doom
62311016
62311016
answered Jun 28 '10 at 14:39
Kyle Slattery
16.7k82635
16.7k82635
3
If you want only the directory name and not the full path, you might do something like this: function getCurrentDirectoryName() { var fullPath = __dirname; var path = fullPath.split('/'); var cwd = path[path.length-1]; return cwd; }
– Anthony Martin
Oct 30 '13 at 20:34
51
@AnthonyMartin __dirname.split("/").pop()
– Kenan Sulayman
Mar 30 '14 at 20:13
5
For those trying @apx solution (like I did:), this solution does not work on Windows.
– Laoujin
May 7 '15 at 19:33
29
Or simply__dirname.split(path.sep).pop()
– Burgi
Jun 11 '15 at 10:53
38
Orrequire('path').basename(__dirname);
– Vyacheslav Cotruta
Oct 5 '15 at 9:03
|
show 5 more comments
3
If you want only the directory name and not the full path, you might do something like this: function getCurrentDirectoryName() { var fullPath = __dirname; var path = fullPath.split('/'); var cwd = path[path.length-1]; return cwd; }
– Anthony Martin
Oct 30 '13 at 20:34
51
@AnthonyMartin __dirname.split("/").pop()
– Kenan Sulayman
Mar 30 '14 at 20:13
5
For those trying @apx solution (like I did:), this solution does not work on Windows.
– Laoujin
May 7 '15 at 19:33
29
Or simply__dirname.split(path.sep).pop()
– Burgi
Jun 11 '15 at 10:53
38
Orrequire('path').basename(__dirname);
– Vyacheslav Cotruta
Oct 5 '15 at 9:03
3
3
If you want only the directory name and not the full path, you might do something like this: function getCurrentDirectoryName() { var fullPath = __dirname; var path = fullPath.split('/'); var cwd = path[path.length-1]; return cwd; }
– Anthony Martin
Oct 30 '13 at 20:34
If you want only the directory name and not the full path, you might do something like this: function getCurrentDirectoryName() { var fullPath = __dirname; var path = fullPath.split('/'); var cwd = path[path.length-1]; return cwd; }
– Anthony Martin
Oct 30 '13 at 20:34
51
51
@AnthonyMartin __dirname.split("/").pop()
– Kenan Sulayman
Mar 30 '14 at 20:13
@AnthonyMartin __dirname.split("/").pop()
– Kenan Sulayman
Mar 30 '14 at 20:13
5
5
For those trying @apx solution (like I did:), this solution does not work on Windows.
– Laoujin
May 7 '15 at 19:33
For those trying @apx solution (like I did:), this solution does not work on Windows.
– Laoujin
May 7 '15 at 19:33
29
29
Or simply
__dirname.split(path.sep).pop()
– Burgi
Jun 11 '15 at 10:53
Or simply
__dirname.split(path.sep).pop()
– Burgi
Jun 11 '15 at 10:53
38
38
Or
require('path').basename(__dirname);
– Vyacheslav Cotruta
Oct 5 '15 at 9:03
Or
require('path').basename(__dirname);
– Vyacheslav Cotruta
Oct 5 '15 at 9:03
|
show 5 more comments
So basically you can do this:
fs.readFile(path.resolve(__dirname, 'settings.json'), 'UTF-8', callback);
Use resolve() instead of concatenating with '/' or '' else you will run into cross-platform issues.
Note: __dirname is the local path of the module or included script. If you are writing a plugin which needs to know the path of the main script it is:
require.main.filename
or, to just get the folder name:
require('path').dirname(require.main.filename)
12
If your goal is just to parse and interact with the json file, you can often do this more easily viavar settings = require('./settings.json')
. Of course, it's synchronous fs IO, so don't do it at run-time, but at startup time it's fine, and once it's loaded, it'll be cached.
– isaacs
May 9 '12 at 18:26
2
@Marc Thanks! For a while now I was hacking my way around the fact that __dirname is local to each module. I have a nested structure in my library and need to know in several places the root of my app. Glad I know how to do this now :D
– Thijs Koerselman
Feb 28 '13 at 14:34
Node V8: path.dirname(process.mainModule.filename)
– wayofthefuture
Aug 26 '17 at 11:47
add a comment |
So basically you can do this:
fs.readFile(path.resolve(__dirname, 'settings.json'), 'UTF-8', callback);
Use resolve() instead of concatenating with '/' or '' else you will run into cross-platform issues.
Note: __dirname is the local path of the module or included script. If you are writing a plugin which needs to know the path of the main script it is:
require.main.filename
or, to just get the folder name:
require('path').dirname(require.main.filename)
12
If your goal is just to parse and interact with the json file, you can often do this more easily viavar settings = require('./settings.json')
. Of course, it's synchronous fs IO, so don't do it at run-time, but at startup time it's fine, and once it's loaded, it'll be cached.
– isaacs
May 9 '12 at 18:26
2
@Marc Thanks! For a while now I was hacking my way around the fact that __dirname is local to each module. I have a nested structure in my library and need to know in several places the root of my app. Glad I know how to do this now :D
– Thijs Koerselman
Feb 28 '13 at 14:34
Node V8: path.dirname(process.mainModule.filename)
– wayofthefuture
Aug 26 '17 at 11:47
add a comment |
So basically you can do this:
fs.readFile(path.resolve(__dirname, 'settings.json'), 'UTF-8', callback);
Use resolve() instead of concatenating with '/' or '' else you will run into cross-platform issues.
Note: __dirname is the local path of the module or included script. If you are writing a plugin which needs to know the path of the main script it is:
require.main.filename
or, to just get the folder name:
require('path').dirname(require.main.filename)
So basically you can do this:
fs.readFile(path.resolve(__dirname, 'settings.json'), 'UTF-8', callback);
Use resolve() instead of concatenating with '/' or '' else you will run into cross-platform issues.
Note: __dirname is the local path of the module or included script. If you are writing a plugin which needs to know the path of the main script it is:
require.main.filename
or, to just get the folder name:
require('path').dirname(require.main.filename)
edited Oct 26 '12 at 17:49
answered Sep 8 '11 at 18:40
Marc
5,28073144
5,28073144
12
If your goal is just to parse and interact with the json file, you can often do this more easily viavar settings = require('./settings.json')
. Of course, it's synchronous fs IO, so don't do it at run-time, but at startup time it's fine, and once it's loaded, it'll be cached.
– isaacs
May 9 '12 at 18:26
2
@Marc Thanks! For a while now I was hacking my way around the fact that __dirname is local to each module. I have a nested structure in my library and need to know in several places the root of my app. Glad I know how to do this now :D
– Thijs Koerselman
Feb 28 '13 at 14:34
Node V8: path.dirname(process.mainModule.filename)
– wayofthefuture
Aug 26 '17 at 11:47
add a comment |
12
If your goal is just to parse and interact with the json file, you can often do this more easily viavar settings = require('./settings.json')
. Of course, it's synchronous fs IO, so don't do it at run-time, but at startup time it's fine, and once it's loaded, it'll be cached.
– isaacs
May 9 '12 at 18:26
2
@Marc Thanks! For a while now I was hacking my way around the fact that __dirname is local to each module. I have a nested structure in my library and need to know in several places the root of my app. Glad I know how to do this now :D
– Thijs Koerselman
Feb 28 '13 at 14:34
Node V8: path.dirname(process.mainModule.filename)
– wayofthefuture
Aug 26 '17 at 11:47
12
12
If your goal is just to parse and interact with the json file, you can often do this more easily via
var settings = require('./settings.json')
. Of course, it's synchronous fs IO, so don't do it at run-time, but at startup time it's fine, and once it's loaded, it'll be cached.– isaacs
May 9 '12 at 18:26
If your goal is just to parse and interact with the json file, you can often do this more easily via
var settings = require('./settings.json')
. Of course, it's synchronous fs IO, so don't do it at run-time, but at startup time it's fine, and once it's loaded, it'll be cached.– isaacs
May 9 '12 at 18:26
2
2
@Marc Thanks! For a while now I was hacking my way around the fact that __dirname is local to each module. I have a nested structure in my library and need to know in several places the root of my app. Glad I know how to do this now :D
– Thijs Koerselman
Feb 28 '13 at 14:34
@Marc Thanks! For a while now I was hacking my way around the fact that __dirname is local to each module. I have a nested structure in my library and need to know in several places the root of my app. Glad I know how to do this now :D
– Thijs Koerselman
Feb 28 '13 at 14:34
Node V8: path.dirname(process.mainModule.filename)
– wayofthefuture
Aug 26 '17 at 11:47
Node V8: path.dirname(process.mainModule.filename)
– wayofthefuture
Aug 26 '17 at 11:47
add a comment |
This command returns the current directory:
var currentPath = process.cwd();
For example, to use the path to read the file:
var fs = require('fs');
fs.readFile(process.cwd() + "\text.txt", function(err, data)
{
if(err)
console.log(err)
else
console.log(data.toString());
});
For those who didn't understand Asynchronous and Synchronous, see this link... stackoverflow.com/a/748235/5287072
– DarckBlezzer
Feb 3 '17 at 17:33
5
this is exactly what the OP doesn't want... the request is for the path of the executable script!
– caesarsol
Mar 29 '18 at 9:10
Current directory is a very different thing. If you run something likecd /foo; node bar/test.js
, current directory would be/foo
, but the script is located in/foo/bar/test.js
.
– rjmunro
Jul 5 '18 at 11:20
add a comment |
This command returns the current directory:
var currentPath = process.cwd();
For example, to use the path to read the file:
var fs = require('fs');
fs.readFile(process.cwd() + "\text.txt", function(err, data)
{
if(err)
console.log(err)
else
console.log(data.toString());
});
For those who didn't understand Asynchronous and Synchronous, see this link... stackoverflow.com/a/748235/5287072
– DarckBlezzer
Feb 3 '17 at 17:33
5
this is exactly what the OP doesn't want... the request is for the path of the executable script!
– caesarsol
Mar 29 '18 at 9:10
Current directory is a very different thing. If you run something likecd /foo; node bar/test.js
, current directory would be/foo
, but the script is located in/foo/bar/test.js
.
– rjmunro
Jul 5 '18 at 11:20
add a comment |
This command returns the current directory:
var currentPath = process.cwd();
For example, to use the path to read the file:
var fs = require('fs');
fs.readFile(process.cwd() + "\text.txt", function(err, data)
{
if(err)
console.log(err)
else
console.log(data.toString());
});
This command returns the current directory:
var currentPath = process.cwd();
For example, to use the path to read the file:
var fs = require('fs');
fs.readFile(process.cwd() + "\text.txt", function(err, data)
{
if(err)
console.log(err)
else
console.log(data.toString());
});
edited Feb 12 '18 at 23:35
dYale
848817
848817
answered Oct 23 '16 at 7:17
Masoud Siahkali
2,0641411
2,0641411
For those who didn't understand Asynchronous and Synchronous, see this link... stackoverflow.com/a/748235/5287072
– DarckBlezzer
Feb 3 '17 at 17:33
5
this is exactly what the OP doesn't want... the request is for the path of the executable script!
– caesarsol
Mar 29 '18 at 9:10
Current directory is a very different thing. If you run something likecd /foo; node bar/test.js
, current directory would be/foo
, but the script is located in/foo/bar/test.js
.
– rjmunro
Jul 5 '18 at 11:20
add a comment |
For those who didn't understand Asynchronous and Synchronous, see this link... stackoverflow.com/a/748235/5287072
– DarckBlezzer
Feb 3 '17 at 17:33
5
this is exactly what the OP doesn't want... the request is for the path of the executable script!
– caesarsol
Mar 29 '18 at 9:10
Current directory is a very different thing. If you run something likecd /foo; node bar/test.js
, current directory would be/foo
, but the script is located in/foo/bar/test.js
.
– rjmunro
Jul 5 '18 at 11:20
For those who didn't understand Asynchronous and Synchronous, see this link... stackoverflow.com/a/748235/5287072
– DarckBlezzer
Feb 3 '17 at 17:33
For those who didn't understand Asynchronous and Synchronous, see this link... stackoverflow.com/a/748235/5287072
– DarckBlezzer
Feb 3 '17 at 17:33
5
5
this is exactly what the OP doesn't want... the request is for the path of the executable script!
– caesarsol
Mar 29 '18 at 9:10
this is exactly what the OP doesn't want... the request is for the path of the executable script!
– caesarsol
Mar 29 '18 at 9:10
Current directory is a very different thing. If you run something like
cd /foo; node bar/test.js
, current directory would be /foo
, but the script is located in /foo/bar/test.js
.– rjmunro
Jul 5 '18 at 11:20
Current directory is a very different thing. If you run something like
cd /foo; node bar/test.js
, current directory would be /foo
, but the script is located in /foo/bar/test.js
.– rjmunro
Jul 5 '18 at 11:20
add a comment |
Use __dirname!!
__dirname
The directory name of the current module. This the same as the path.dirname() of the __filename
.
Example: running node example.js from /Users/mjr
console.log(__dirname);
// Prints: /Users/mjr
console.log(path.dirname(__filename));
// Prints: /Users/mjr
https://nodejs.org/api/modules.html#modules_dirname
1
This survives symlinks too. So if you create a bin and need to find a file, eg path.join(__dirname, "../example.json"); it will still work when your binary is linked in node_modules/.bin
– Jason
Apr 17 '18 at 17:12
add a comment |
Use __dirname!!
__dirname
The directory name of the current module. This the same as the path.dirname() of the __filename
.
Example: running node example.js from /Users/mjr
console.log(__dirname);
// Prints: /Users/mjr
console.log(path.dirname(__filename));
// Prints: /Users/mjr
https://nodejs.org/api/modules.html#modules_dirname
1
This survives symlinks too. So if you create a bin and need to find a file, eg path.join(__dirname, "../example.json"); it will still work when your binary is linked in node_modules/.bin
– Jason
Apr 17 '18 at 17:12
add a comment |
Use __dirname!!
__dirname
The directory name of the current module. This the same as the path.dirname() of the __filename
.
Example: running node example.js from /Users/mjr
console.log(__dirname);
// Prints: /Users/mjr
console.log(path.dirname(__filename));
// Prints: /Users/mjr
https://nodejs.org/api/modules.html#modules_dirname
Use __dirname!!
__dirname
The directory name of the current module. This the same as the path.dirname() of the __filename
.
Example: running node example.js from /Users/mjr
console.log(__dirname);
// Prints: /Users/mjr
console.log(path.dirname(__filename));
// Prints: /Users/mjr
https://nodejs.org/api/modules.html#modules_dirname
edited Apr 29 '18 at 12:56
answered Dec 22 '17 at 14:30
Azarus
917821
917821
1
This survives symlinks too. So if you create a bin and need to find a file, eg path.join(__dirname, "../example.json"); it will still work when your binary is linked in node_modules/.bin
– Jason
Apr 17 '18 at 17:12
add a comment |
1
This survives symlinks too. So if you create a bin and need to find a file, eg path.join(__dirname, "../example.json"); it will still work when your binary is linked in node_modules/.bin
– Jason
Apr 17 '18 at 17:12
1
1
This survives symlinks too. So if you create a bin and need to find a file, eg path.join(__dirname, "../example.json"); it will still work when your binary is linked in node_modules/.bin
– Jason
Apr 17 '18 at 17:12
This survives symlinks too. So if you create a bin and need to find a file, eg path.join(__dirname, "../example.json"); it will still work when your binary is linked in node_modules/.bin
– Jason
Apr 17 '18 at 17:12
add a comment |
When it comes to the main script it's as simple as:
process.argv[1]
From the Node.js documentation:
process.argv
An array containing the command line arguments. The first element will be 'node', the second element will be the path to the JavaScript file. The next elements will be any additional command line arguments.
If you need to know the path of a module file then use __filename.
3
Could the downvoter please explain why this is not recommended?
– Tamlyn
Jan 15 '16 at 16:57
1
@Tamlyn Maybe becauseprocess.argv[1]
applies only to the main script while__filename
points to the module file being executed. I update my answer to emphasize the difference. Still, I see nothing wrong in usingprocess.argv[1]
. Depends on one's requirements.
– Lukasz Wiktor
Jan 16 '16 at 6:40
1
@Tamlyn Not good when you think about testing.
– Karl Morrison
Sep 23 '16 at 8:56
7
If main script was launched with a node process manager like pm2 process.argv[1] will point to the executable of the process manager /usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js
– user3002996
Mar 1 '17 at 11:28
add a comment |
When it comes to the main script it's as simple as:
process.argv[1]
From the Node.js documentation:
process.argv
An array containing the command line arguments. The first element will be 'node', the second element will be the path to the JavaScript file. The next elements will be any additional command line arguments.
If you need to know the path of a module file then use __filename.
3
Could the downvoter please explain why this is not recommended?
– Tamlyn
Jan 15 '16 at 16:57
1
@Tamlyn Maybe becauseprocess.argv[1]
applies only to the main script while__filename
points to the module file being executed. I update my answer to emphasize the difference. Still, I see nothing wrong in usingprocess.argv[1]
. Depends on one's requirements.
– Lukasz Wiktor
Jan 16 '16 at 6:40
1
@Tamlyn Not good when you think about testing.
– Karl Morrison
Sep 23 '16 at 8:56
7
If main script was launched with a node process manager like pm2 process.argv[1] will point to the executable of the process manager /usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js
– user3002996
Mar 1 '17 at 11:28
add a comment |
When it comes to the main script it's as simple as:
process.argv[1]
From the Node.js documentation:
process.argv
An array containing the command line arguments. The first element will be 'node', the second element will be the path to the JavaScript file. The next elements will be any additional command line arguments.
If you need to know the path of a module file then use __filename.
When it comes to the main script it's as simple as:
process.argv[1]
From the Node.js documentation:
process.argv
An array containing the command line arguments. The first element will be 'node', the second element will be the path to the JavaScript file. The next elements will be any additional command line arguments.
If you need to know the path of a module file then use __filename.
edited Dec 17 '17 at 10:35
adelriosantiago
2,0201838
2,0201838
answered Dec 17 '15 at 10:41
Lukasz Wiktor
11.2k24861
11.2k24861
3
Could the downvoter please explain why this is not recommended?
– Tamlyn
Jan 15 '16 at 16:57
1
@Tamlyn Maybe becauseprocess.argv[1]
applies only to the main script while__filename
points to the module file being executed. I update my answer to emphasize the difference. Still, I see nothing wrong in usingprocess.argv[1]
. Depends on one's requirements.
– Lukasz Wiktor
Jan 16 '16 at 6:40
1
@Tamlyn Not good when you think about testing.
– Karl Morrison
Sep 23 '16 at 8:56
7
If main script was launched with a node process manager like pm2 process.argv[1] will point to the executable of the process manager /usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js
– user3002996
Mar 1 '17 at 11:28
add a comment |
3
Could the downvoter please explain why this is not recommended?
– Tamlyn
Jan 15 '16 at 16:57
1
@Tamlyn Maybe becauseprocess.argv[1]
applies only to the main script while__filename
points to the module file being executed. I update my answer to emphasize the difference. Still, I see nothing wrong in usingprocess.argv[1]
. Depends on one's requirements.
– Lukasz Wiktor
Jan 16 '16 at 6:40
1
@Tamlyn Not good when you think about testing.
– Karl Morrison
Sep 23 '16 at 8:56
7
If main script was launched with a node process manager like pm2 process.argv[1] will point to the executable of the process manager /usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js
– user3002996
Mar 1 '17 at 11:28
3
3
Could the downvoter please explain why this is not recommended?
– Tamlyn
Jan 15 '16 at 16:57
Could the downvoter please explain why this is not recommended?
– Tamlyn
Jan 15 '16 at 16:57
1
1
@Tamlyn Maybe because
process.argv[1]
applies only to the main script while __filename
points to the module file being executed. I update my answer to emphasize the difference. Still, I see nothing wrong in using process.argv[1]
. Depends on one's requirements.– Lukasz Wiktor
Jan 16 '16 at 6:40
@Tamlyn Maybe because
process.argv[1]
applies only to the main script while __filename
points to the module file being executed. I update my answer to emphasize the difference. Still, I see nothing wrong in using process.argv[1]
. Depends on one's requirements.– Lukasz Wiktor
Jan 16 '16 at 6:40
1
1
@Tamlyn Not good when you think about testing.
– Karl Morrison
Sep 23 '16 at 8:56
@Tamlyn Not good when you think about testing.
– Karl Morrison
Sep 23 '16 at 8:56
7
7
If main script was launched with a node process manager like pm2 process.argv[1] will point to the executable of the process manager /usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js
– user3002996
Mar 1 '17 at 11:28
If main script was launched with a node process manager like pm2 process.argv[1] will point to the executable of the process manager /usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js
– user3002996
Mar 1 '17 at 11:28
add a comment |
var settings =
JSON.parse(
require('fs').readFileSync(
require('path').resolve(
__dirname,
'settings.json'),
'utf8'));
7
Just a note, as of node 0.5 you can just require a JSON file. Of course that wouldn't answer the question.
– Kevin Cox
Apr 9 '13 at 21:18
add a comment |
var settings =
JSON.parse(
require('fs').readFileSync(
require('path').resolve(
__dirname,
'settings.json'),
'utf8'));
7
Just a note, as of node 0.5 you can just require a JSON file. Of course that wouldn't answer the question.
– Kevin Cox
Apr 9 '13 at 21:18
add a comment |
var settings =
JSON.parse(
require('fs').readFileSync(
require('path').resolve(
__dirname,
'settings.json'),
'utf8'));
var settings =
JSON.parse(
require('fs').readFileSync(
require('path').resolve(
__dirname,
'settings.json'),
'utf8'));
edited Mar 30 '14 at 4:38
Community♦
11
11
answered Nov 5 '12 at 5:41
foobar
26932
26932
7
Just a note, as of node 0.5 you can just require a JSON file. Of course that wouldn't answer the question.
– Kevin Cox
Apr 9 '13 at 21:18
add a comment |
7
Just a note, as of node 0.5 you can just require a JSON file. Of course that wouldn't answer the question.
– Kevin Cox
Apr 9 '13 at 21:18
7
7
Just a note, as of node 0.5 you can just require a JSON file. Of course that wouldn't answer the question.
– Kevin Cox
Apr 9 '13 at 21:18
Just a note, as of node 0.5 you can just require a JSON file. Of course that wouldn't answer the question.
– Kevin Cox
Apr 9 '13 at 21:18
add a comment |
Every Node.js program has some global variables in its environment, which represents some information about your process and one of it is __dirname
.
add a comment |
Every Node.js program has some global variables in its environment, which represents some information about your process and one of it is __dirname
.
add a comment |
Every Node.js program has some global variables in its environment, which represents some information about your process and one of it is __dirname
.
Every Node.js program has some global variables in its environment, which represents some information about your process and one of it is __dirname
.
edited Feb 26 '17 at 10:10
Omar Ali
6,21142756
6,21142756
answered May 25 '16 at 21:27
Hazarapet Tunanyan
1,4861318
1,4861318
add a comment |
add a comment |
You can use process.env.PWD to get the current app folder path.
1
OP asks for the requested "path to the script". PWD, which stands for something like Process Working Directory, is not that. Also, the "current app" phrasing is misleading.
– dmcontador
Sep 8 '17 at 6:48
add a comment |
You can use process.env.PWD to get the current app folder path.
1
OP asks for the requested "path to the script". PWD, which stands for something like Process Working Directory, is not that. Also, the "current app" phrasing is misleading.
– dmcontador
Sep 8 '17 at 6:48
add a comment |
You can use process.env.PWD to get the current app folder path.
You can use process.env.PWD to get the current app folder path.
answered Sep 28 '16 at 7:00
AbiSivam
189315
189315
1
OP asks for the requested "path to the script". PWD, which stands for something like Process Working Directory, is not that. Also, the "current app" phrasing is misleading.
– dmcontador
Sep 8 '17 at 6:48
add a comment |
1
OP asks for the requested "path to the script". PWD, which stands for something like Process Working Directory, is not that. Also, the "current app" phrasing is misleading.
– dmcontador
Sep 8 '17 at 6:48
1
1
OP asks for the requested "path to the script". PWD, which stands for something like Process Working Directory, is not that. Also, the "current app" phrasing is misleading.
– dmcontador
Sep 8 '17 at 6:48
OP asks for the requested "path to the script". PWD, which stands for something like Process Working Directory, is not that. Also, the "current app" phrasing is misleading.
– dmcontador
Sep 8 '17 at 6:48
add a comment |
I know this is pretty old, and the original question I was responding to is marked as duplicate and directed here, but I ran into an issue trying to get jasmine-reporters to work and didn't like the idea that I had to downgrade in order for it to work. I found out that jasmine-reporters wasn't resolving the savePath correctly and was actually putting the reports folder output in jasmine-reporters directory instead of the root directory of where I ran gulp. In order to make this work correctly I ended up using process.env.INIT_CWD to get the initial Current Working Directory which should be the directory where you ran gulp. Hope this helps someone.
var reporters = require('jasmine-reporters');
var junitReporter = new reporters.JUnitXmlReporter({
savePath: process.env.INIT_CWD + '/report/e2e/',
consolidateAll: true,
captureStdout: true
});
god bless you, this is what I was looking for! you are my source of pure awesomeness for this day!
– YangombiUmpakati
Nov 16 '18 at 11:09
add a comment |
I know this is pretty old, and the original question I was responding to is marked as duplicate and directed here, but I ran into an issue trying to get jasmine-reporters to work and didn't like the idea that I had to downgrade in order for it to work. I found out that jasmine-reporters wasn't resolving the savePath correctly and was actually putting the reports folder output in jasmine-reporters directory instead of the root directory of where I ran gulp. In order to make this work correctly I ended up using process.env.INIT_CWD to get the initial Current Working Directory which should be the directory where you ran gulp. Hope this helps someone.
var reporters = require('jasmine-reporters');
var junitReporter = new reporters.JUnitXmlReporter({
savePath: process.env.INIT_CWD + '/report/e2e/',
consolidateAll: true,
captureStdout: true
});
god bless you, this is what I was looking for! you are my source of pure awesomeness for this day!
– YangombiUmpakati
Nov 16 '18 at 11:09
add a comment |
I know this is pretty old, and the original question I was responding to is marked as duplicate and directed here, but I ran into an issue trying to get jasmine-reporters to work and didn't like the idea that I had to downgrade in order for it to work. I found out that jasmine-reporters wasn't resolving the savePath correctly and was actually putting the reports folder output in jasmine-reporters directory instead of the root directory of where I ran gulp. In order to make this work correctly I ended up using process.env.INIT_CWD to get the initial Current Working Directory which should be the directory where you ran gulp. Hope this helps someone.
var reporters = require('jasmine-reporters');
var junitReporter = new reporters.JUnitXmlReporter({
savePath: process.env.INIT_CWD + '/report/e2e/',
consolidateAll: true,
captureStdout: true
});
I know this is pretty old, and the original question I was responding to is marked as duplicate and directed here, but I ran into an issue trying to get jasmine-reporters to work and didn't like the idea that I had to downgrade in order for it to work. I found out that jasmine-reporters wasn't resolving the savePath correctly and was actually putting the reports folder output in jasmine-reporters directory instead of the root directory of where I ran gulp. In order to make this work correctly I ended up using process.env.INIT_CWD to get the initial Current Working Directory which should be the directory where you ran gulp. Hope this helps someone.
var reporters = require('jasmine-reporters');
var junitReporter = new reporters.JUnitXmlReporter({
savePath: process.env.INIT_CWD + '/report/e2e/',
consolidateAll: true,
captureStdout: true
});
var reporters = require('jasmine-reporters');
var junitReporter = new reporters.JUnitXmlReporter({
savePath: process.env.INIT_CWD + '/report/e2e/',
consolidateAll: true,
captureStdout: true
});
var reporters = require('jasmine-reporters');
var junitReporter = new reporters.JUnitXmlReporter({
savePath: process.env.INIT_CWD + '/report/e2e/',
consolidateAll: true,
captureStdout: true
});
answered Mar 15 '17 at 15:37
Dana Harris
10114
10114
god bless you, this is what I was looking for! you are my source of pure awesomeness for this day!
– YangombiUmpakati
Nov 16 '18 at 11:09
add a comment |
god bless you, this is what I was looking for! you are my source of pure awesomeness for this day!
– YangombiUmpakati
Nov 16 '18 at 11:09
god bless you, this is what I was looking for! you are my source of pure awesomeness for this day!
– YangombiUmpakati
Nov 16 '18 at 11:09
god bless you, this is what I was looking for! you are my source of pure awesomeness for this day!
– YangombiUmpakati
Nov 16 '18 at 11:09
add a comment |
Node.js 10 supports ECMAScript modules, where __dirname
and __filename
are not available out of the box.
Then to get the path to the current ES module one has to use:
const __filename = new URL(import.meta.url).pathname;
And for the directory containing the current module:
import path from 'path';
const __dirname = path.dirname(new URL(import.meta.url).pathname);
add a comment |
Node.js 10 supports ECMAScript modules, where __dirname
and __filename
are not available out of the box.
Then to get the path to the current ES module one has to use:
const __filename = new URL(import.meta.url).pathname;
And for the directory containing the current module:
import path from 'path';
const __dirname = path.dirname(new URL(import.meta.url).pathname);
add a comment |
Node.js 10 supports ECMAScript modules, where __dirname
and __filename
are not available out of the box.
Then to get the path to the current ES module one has to use:
const __filename = new URL(import.meta.url).pathname;
And for the directory containing the current module:
import path from 'path';
const __dirname = path.dirname(new URL(import.meta.url).pathname);
Node.js 10 supports ECMAScript modules, where __dirname
and __filename
are not available out of the box.
Then to get the path to the current ES module one has to use:
const __filename = new URL(import.meta.url).pathname;
And for the directory containing the current module:
import path from 'path';
const __dirname = path.dirname(new URL(import.meta.url).pathname);
answered Apr 27 '18 at 1:01
GOTO 0
15.9k1275111
15.9k1275111
add a comment |
add a comment |
If you are using pkg
to package your app, you'll find useful this expression:
appDirectory = require('path').dirname(process.pkg ? process.execPath : (require.main ? require.main.filename : process.argv[0]));
process.pkg
tells if the app has been packaged bypkg
.process.execPath
holds the full path of the executable, which is/usr/bin/node
or similar for direct invocations of scripts (node test.js
), or the packaged app.require.main.filename
holds the full path of the main script, but it's empty when Node runs in interactive mode.__dirname
holds the full path of the current script, so I'm not using it (although it may be what OP asks; then better useappDirectory = process.pkg ? require('path').dirname(process.execPath) : (__dirname || require('path').dirname(process.argv[0]));
noting that in interactive mode__dirname
is empty.For interactive mode, use either
process.argv[0]
to get the path to the Node executable orprocess.cwd()
to get the current directory.
Exactly what I was looking for, thanks.
– James Bruckner
Aug 18 '18 at 18:37
add a comment |
If you are using pkg
to package your app, you'll find useful this expression:
appDirectory = require('path').dirname(process.pkg ? process.execPath : (require.main ? require.main.filename : process.argv[0]));
process.pkg
tells if the app has been packaged bypkg
.process.execPath
holds the full path of the executable, which is/usr/bin/node
or similar for direct invocations of scripts (node test.js
), or the packaged app.require.main.filename
holds the full path of the main script, but it's empty when Node runs in interactive mode.__dirname
holds the full path of the current script, so I'm not using it (although it may be what OP asks; then better useappDirectory = process.pkg ? require('path').dirname(process.execPath) : (__dirname || require('path').dirname(process.argv[0]));
noting that in interactive mode__dirname
is empty.For interactive mode, use either
process.argv[0]
to get the path to the Node executable orprocess.cwd()
to get the current directory.
Exactly what I was looking for, thanks.
– James Bruckner
Aug 18 '18 at 18:37
add a comment |
If you are using pkg
to package your app, you'll find useful this expression:
appDirectory = require('path').dirname(process.pkg ? process.execPath : (require.main ? require.main.filename : process.argv[0]));
process.pkg
tells if the app has been packaged bypkg
.process.execPath
holds the full path of the executable, which is/usr/bin/node
or similar for direct invocations of scripts (node test.js
), or the packaged app.require.main.filename
holds the full path of the main script, but it's empty when Node runs in interactive mode.__dirname
holds the full path of the current script, so I'm not using it (although it may be what OP asks; then better useappDirectory = process.pkg ? require('path').dirname(process.execPath) : (__dirname || require('path').dirname(process.argv[0]));
noting that in interactive mode__dirname
is empty.For interactive mode, use either
process.argv[0]
to get the path to the Node executable orprocess.cwd()
to get the current directory.
If you are using pkg
to package your app, you'll find useful this expression:
appDirectory = require('path').dirname(process.pkg ? process.execPath : (require.main ? require.main.filename : process.argv[0]));
process.pkg
tells if the app has been packaged bypkg
.process.execPath
holds the full path of the executable, which is/usr/bin/node
or similar for direct invocations of scripts (node test.js
), or the packaged app.require.main.filename
holds the full path of the main script, but it's empty when Node runs in interactive mode.__dirname
holds the full path of the current script, so I'm not using it (although it may be what OP asks; then better useappDirectory = process.pkg ? require('path').dirname(process.execPath) : (__dirname || require('path').dirname(process.argv[0]));
noting that in interactive mode__dirname
is empty.For interactive mode, use either
process.argv[0]
to get the path to the Node executable orprocess.cwd()
to get the current directory.
answered Sep 8 '17 at 7:28
dmcontador
313113
313113
Exactly what I was looking for, thanks.
– James Bruckner
Aug 18 '18 at 18:37
add a comment |
Exactly what I was looking for, thanks.
– James Bruckner
Aug 18 '18 at 18:37
Exactly what I was looking for, thanks.
– James Bruckner
Aug 18 '18 at 18:37
Exactly what I was looking for, thanks.
– James Bruckner
Aug 18 '18 at 18:37
add a comment |
If you want something more like $0 in a shell script, try this:
var path = require('path');
var command = getCurrentScriptPath();
console.log(`Usage: ${command} <foo> <bar>`);
function getCurrentScriptPath () {
// Relative path from current working directory to the location of this script
var pathToScript = path.relative(process.cwd(), __filename);
// Check if current working dir is the same as the script
if (process.cwd() === __dirname) {
// E.g. "./foobar.js"
return '.' + path.sep + pathToScript;
} else {
// E.g. "foo/bar/baz.js"
return pathToScript;
}
}
add a comment |
If you want something more like $0 in a shell script, try this:
var path = require('path');
var command = getCurrentScriptPath();
console.log(`Usage: ${command} <foo> <bar>`);
function getCurrentScriptPath () {
// Relative path from current working directory to the location of this script
var pathToScript = path.relative(process.cwd(), __filename);
// Check if current working dir is the same as the script
if (process.cwd() === __dirname) {
// E.g. "./foobar.js"
return '.' + path.sep + pathToScript;
} else {
// E.g. "foo/bar/baz.js"
return pathToScript;
}
}
add a comment |
If you want something more like $0 in a shell script, try this:
var path = require('path');
var command = getCurrentScriptPath();
console.log(`Usage: ${command} <foo> <bar>`);
function getCurrentScriptPath () {
// Relative path from current working directory to the location of this script
var pathToScript = path.relative(process.cwd(), __filename);
// Check if current working dir is the same as the script
if (process.cwd() === __dirname) {
// E.g. "./foobar.js"
return '.' + path.sep + pathToScript;
} else {
// E.g. "foo/bar/baz.js"
return pathToScript;
}
}
If you want something more like $0 in a shell script, try this:
var path = require('path');
var command = getCurrentScriptPath();
console.log(`Usage: ${command} <foo> <bar>`);
function getCurrentScriptPath () {
// Relative path from current working directory to the location of this script
var pathToScript = path.relative(process.cwd(), __filename);
// Check if current working dir is the same as the script
if (process.cwd() === __dirname) {
// E.g. "./foobar.js"
return '.' + path.sep + pathToScript;
} else {
// E.g. "foo/bar/baz.js"
return pathToScript;
}
}
answered May 5 '17 at 9:32
dmayo3
745
745
add a comment |
add a comment |
Another approach, if you're using modules and you'd like to find the filename of the main module that called such sub-module or any module you're running, is to use
var fnArr = (process.mainModule.filename).split('/');
var filename = fnArr[fnArr.length -1];
2
NEVER usesplit
for directories! usepath.dirname
!
– caesarsol
Mar 29 '18 at 9:06
1
@caesarsol good point! Thank you
– João Pimentel Ferreira
Mar 29 '18 at 17:07
add a comment |
Another approach, if you're using modules and you'd like to find the filename of the main module that called such sub-module or any module you're running, is to use
var fnArr = (process.mainModule.filename).split('/');
var filename = fnArr[fnArr.length -1];
2
NEVER usesplit
for directories! usepath.dirname
!
– caesarsol
Mar 29 '18 at 9:06
1
@caesarsol good point! Thank you
– João Pimentel Ferreira
Mar 29 '18 at 17:07
add a comment |
Another approach, if you're using modules and you'd like to find the filename of the main module that called such sub-module or any module you're running, is to use
var fnArr = (process.mainModule.filename).split('/');
var filename = fnArr[fnArr.length -1];
Another approach, if you're using modules and you'd like to find the filename of the main module that called such sub-module or any module you're running, is to use
var fnArr = (process.mainModule.filename).split('/');
var filename = fnArr[fnArr.length -1];
answered Feb 9 '18 at 19:29
João Pimentel Ferreira
3,80612128
3,80612128
2
NEVER usesplit
for directories! usepath.dirname
!
– caesarsol
Mar 29 '18 at 9:06
1
@caesarsol good point! Thank you
– João Pimentel Ferreira
Mar 29 '18 at 17:07
add a comment |
2
NEVER usesplit
for directories! usepath.dirname
!
– caesarsol
Mar 29 '18 at 9:06
1
@caesarsol good point! Thank you
– João Pimentel Ferreira
Mar 29 '18 at 17:07
2
2
NEVER use
split
for directories! use path.dirname
!– caesarsol
Mar 29 '18 at 9:06
NEVER use
split
for directories! use path.dirname
!– caesarsol
Mar 29 '18 at 9:06
1
1
@caesarsol good point! Thank you
– João Pimentel Ferreira
Mar 29 '18 at 17:07
@caesarsol good point! Thank you
– João Pimentel Ferreira
Mar 29 '18 at 17:07
add a comment |
protected by eyllanesc Aug 14 '18 at 18:56
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
4
nodejs.org/docs/latest/api/globals.html the documentation link of the accepted answer.
– allenhwkim
Apr 12 '13 at 15:41