2

I want the equivalent of $PROGRAM_NAME in Ruby, or ARGV[0] in C-likes, for Node.js. When I have a Node script that looks something like this,

#!/usr/bin/env node
console.log(process.argv[0])

… I get “node” instead of the name of the file that code is saved in. How do I get around this?

3 Answers 3

4

You can either use this (if called from your main.js file):

var path = require('path');
var programName = path.basename(__filename);

Or this, anywhere:

var path = require('path');
var programName = path.basename(process.argv[1]);
1
  • I really wish there was a more direct way, but the latter seems to answer my question. I'm still afraid of edge-cases that it seems not to cover, but I can't pinpoint one, so I'm accepting this. (= May 11, 2013 at 0:27
1

Use __filename? It returns the currently executing script.

http://nodejs.org/docs/latest/api/globals.html#globals_filename

1
  • That, however, won't tell me what it was invoked as. That will fail with symlinks, or with wrapper-scripts such as those npm uses, or anything else of that flavour. May 11, 2013 at 0:21
-2

For working with command line option strings check out the optimist module by Substack. Optimist will make your life much easier.

var inspect = require('eyespect').inspector();
var optimist = require('optimist')
var path = require('path');
var argv = optimist.argv
inspect(argv, 'argv')
var programName = path.basename(__filename);
inspect(programName, 'programName')

To install the needed dependencies:

npm install -S eyespect optimist
1
  • -1 for pushing your own modules, without declaration; not to mention that I clearly asked for a way to do so in Node.js, without pulling in extra modules. (That said, Optimist is great; it's just inapplicable in this situation. NPM is not always the solution, nor always an option.) May 11, 2013 at 0:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.