Aardo
Aardo

Reputation: 227

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?

Upvotes: 1

Views: 10791

Answers (3)

Aer0
Aer0

Reputation: 3907

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.

Upvotes: 3

libik
libik

Reputation: 23029

Your run your file: node server.js

Then it starts.

There should be specified in code on which port you run your server. Then it is accessible for example at http://localhost:3000/


As Quentin noted, I was thinking about "creating web server". Of course, you can run javascript code with Node.js without server. Then skip the part abot localhost, just use node test.js in console.

Upvotes: 0

Ahmed farag mostafa
Ahmed farag mostafa

Reputation: 2934

you can use these packages to keep the file running so you won't have to login to server every time :-

forever and you can just write :-

forever start app.js

nodemon

nodemon app.js

pm2 which is very useful , as it will auto restart your app when it crash or any error happens

pm2 start app.js

Upvotes: 2

Related Questions