P.Brian.Mackey
P.Brian.Mackey

Reputation: 44275

How to execute a file in windows using NodeJS?

I installed Nodejs and I'm using it for the first time. The API is a bit too generic. The first example does not explain how to specify a file path. I setup the testFile.js with the code:

var http = require('http');

http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type':     
'text/plain'});
  response.end('Hello World\n');
}).listen(8124);

console.log('Server running at     
http://127.0.0.1:8124/');

I verified node.js is correctly installed by typing "node <enter> 1 + 1" and got a response of "2". Then I tried:

>node "C:\path\testNode.js"

This returns ... which is no different than passing an incorrect file

>node "C:\INCORRECTPATH\testNode.js"

Then I tried dropping the parenthesis, still no work. Also tried doing a change directory before running "node" command. Guess what! Still no worky. The error ... is super useful, but I just dunno how to fix it..?

What's the syntax?

Upvotes: 2

Views: 3314

Answers (2)

P.Brian.Mackey
P.Brian.Mackey

Reputation: 44275

UPDATE

<AnticlimacticConclusion>
Restarting the computer corrected the problem.
</AnticlimacticConclusion>

So node.js did install. And it even gave results (remember in the OP 1 + 1 returns 2). But, the PATH remained jacked up for whatever reason. (Yes I tried a new instance of cmd).

(The rest of this post is old information for reference only)

What did not work

The commands did not function when I went to the command prompt via:

start > run > cmd > node C:\path\testNode.js

It also did not function with a shortcut I had in my start menu to an admin mode version of cmd which links to:

%comspec% /k ""C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\Tools\VsDevCmd.bat""

What worked

I ran a search on my PC and found a program entitled "Node.js command prompt". The shortcut on my machine pointed to:

C:\Windows\System32\cmd.exe /k "C:\Program Files\nodejs\nodevars.bat"

When I run node commands with this batch file pre-loaded then everything works out. E.G.

> node C:\path\testNode.js

returns Server running at http://127.0.0.1:8124/. A picture says 1000 words. Note the first line. enter image description here

In other words, it appears this batch file is required.

Upvotes: 1

kybernetikos
kybernetikos

Reputation: 8689

It looks like you're executing the node command inside a node repl.

This would happen if you are working in the window that pops up when you click a "Node.js" icon in your start menu.

To execute it in the way you've tried, run it from a normal command prompt. i.e. hit windows-r, type cmd, press return, or find Command Prompt in your start menu.

You can also run an external node script from inside the node repl by requiring it.

 require("C:\\path\\testNode.js")

This will only work the first time as it is cached for subsequent require calls.

Upvotes: 0

Related Questions