Run A Node.js Project

 

Node.js is run by typing the command below from inside the project folder.

npm start

For example, if we are holding our project in a folder called "c:\nodejs_projects\server_test", then we run the command line "npm start", as shown below, to start the Node.js server-side code. We shall see this running in the example that follows:

Closing the cmd window or pressing the Ctrl C keys will terminate the server-side code. Whenever Windows is shut-down, the cmd windows will be closed. Therefore, the server-side code must be restarted whenever the sytem boots-up.

Node.js Project Example

Create a folder called "server_test" to hold your project and a sub-folder called "public" to hold the index.html file.

Create the index.html file below and place it in the "public" folder of your project.

index.html
<!DOCTYPE HTML> 
<html> 
    <head>
        <meta charset="UTF-8" /> 
        <title>Node.js Server Test</title> 
    </head>
    <body> 
        <h1>Node.js Server Test</h1>
        <p>If you see this text output, then you have successfully set up a Node.js server.</p>
    </body> 
</html>

Create the server.js file below and place it in the "server_test" folder. Do not worry about the content of this file for the moment. We shall describe this in detail later on in these notes.

server.js
const express = require('express');
const app = express();
app.use(express.static('public'));
app.listen(3000, function()
{
    console.log('App running on port 3000');
});

From inside the "server_test" folder, type the command below.

npm start

This will cause Node.js to run on port 3000.

In your browser, open the url "localhost:3000". You should see the webpage below.

Close and restart the server-side by closing the cmd window and by using the Ctrl C keys.

 
<div align="center"><a href="../../versionC/index.html" title="DKIT Lecture notes homepage for Derek O&#39; Reilly, Dundalk Institute of Technology (DKIT), Dundalk, County Louth, Ireland. Copyright Derek O&#39; Reilly, DKIT." target="_parent" style='font-size:0;color:white;background-color:white'>&nbsp;</a></div>