Aardenon Aardenon - 1 year ago 115
Javascript Question

How to execute a Node.js script on the server?

I'm beginning to learn web technologies and programming and I'm setting up my own local webserver. I have HTTPD, PHP, Python, MySQL all up and running on Windows. Now I want to add Node.js to the mix. I installed the Windows 64 bit installer. Now how do I begin? I have a basic Hello World script in a test.js file. But when I access this file in the browser it only displays as plain text. It's not executed. How to execute a Node.js script on the server?

Answer Source

Starting a node script is pretty simple. Just use your command line or terminal and execute the following command.

node /path/to/your/file.js

Doing so you'll start your node script. If you're going to start a server it's pretty much the same. Just keep in mind to define a server in your node file and start it. A simple server using express could look like this (You can also use a fully node way, this is just a simple example using express. You may check google for how to set up a simple node http server).

var express = require('express');
var app = express();
var port = 4000;

app.listen(process.env.port || port);

As you can see the specified port is set to 4000. You can simply adjust this by changing the value itself or passing in a node environment variable. To pass in an environment variable just start your server like this.

node port=3000 /path/to/your/file.js

This will finally pass the value of port to process.env.port which obviously will start your server on the port 3000.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download