ELLIOTTCABLE
ELLIOTTCABLE

Reputation: 18038

How do I get the ‘program name’ (invocation location) in Node.js?

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?

Upvotes: 2

Views: 2831

Answers (3)

Noah
Noah

Reputation: 34313

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

Upvotes: -2

user703016
user703016

Reputation: 37945

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]);

Upvotes: 4

Matthew Graves
Matthew Graves

Reputation: 3284

Use __filename? It returns the currently executing script.

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

Upvotes: 1

Related Questions