1

I have a simple JavaScript myScript.js with code as below;

var printer = function(someString){
    console.log(someString);
}

printer("This is printed on console.");

I'm on Windows 10 and need to be able to call myScript.js on a command prompt and have the code executed without doing node myScript.js. Is there a way to set up things so that Command prompt or PowerShell can automatically call Nodejs or other JavaScript engine?

T-Heron
  • 5,385
  • 7
  • 26
  • 52
Amani
  • 16,245
  • 29
  • 103
  • 153

1 Answers1

2

If your Windows can run normal shell scripts on the command line then you can add a shebang line to your Node script just like you do with shell scripts. For example:

#!/usr/bin/env node
// your node code here

Also you can try to configure Node to be invoked for all files with the .js extension but this can be a security hazard because you may execute arbitrary code just by clocking on JavaScript files that you may have downloaded on your system so I wouldn't really recommend that.

Another alternative is to make a BAT script for you Node app:

example.bat:

node example.js

example.js:

// your Node script

That you will be able to run with just:

example

on your command line.

rsp
  • 107,747
  • 29
  • 201
  • 177