By default, Windows associates .js
files with the Windows Script Host, Microsoft's stand-alone JS runtime engine. If you type script.js at a command prompt (or double-click a .js
file in Explorer), the script is executed by wscript.exe
.
This may be solving a local problem with a global setting, but you could associate .js
files with node.exe
instead, so that typing script.js at a command prompt or double-clicking/dragging items onto scripts will launch them with Node.
Of course, if—like me—you've associated .js
files with an editor so that double-clicking them opens up your favorite text editor, this suggestion won't do much good. You could also add a right-click menu entry of "Execute with Node" to .js
files, although this alternative doesn't solve your command-line needs.
The simplest solution is probably to just use a batch file – you don't have to have a copy of Node in the folder your script resides in. Just reference the Node executable absolutely:
"C:\Program Files (x86)\nodejs\node.exe" app.js %*
Another alternative is this very simple C# app which will start Node using its own filename + .js
as the script to run, and pass along any command line arguments.
class Program
{
static void Main(string[] args)
{
var info = System.Diagnostics.Process.GetCurrentProcess();
var proc = new System.Diagnostics.ProcessStartInfo(@"C:\Program Files (x86)\nodejs\node.exe", "\"" + info.ProcessName + ".js\" " + String.Join(" ", args));
proc.UseShellExecute = false;
System.Diagnostics.Process.Start(proc);
}
}
So if you name the resulting EXE "app.exe", you can type app arg1 ...
and Node will be started with the command line "app.js" arg1 ...
. Note the C# bootstrapper app will immediately exit, leaving Node in charge of the console window.
Since this is probably of relatively wide interest, I went ahead and made this available on GitHub, including the compiled exe if getting in to vans with strangers is your thing.