Node.js – Lesson 5: Create Web-server application

First create file app.js:

const express = require("express");
const app = express();
const port = 8000;

app.listen(port, () => {
    console.log("Server work on "+port); 
});

In this code we require Express framework that provides a robust set of features for web and mobile applications. Define class app – our main application class and port – default server port.

We can start our server using command:

npm run start

But now our server can not do nothing, ot only write in console text: “Server work on port 8000“. Let’s create routing and say our server how to work with Url and write text to Web-browser.

First create folder “routes” and file “routes/index.js” with code:

const mainRoutes = require('./main');

module.exports = function(app) {
    mainRoutes(app);
}

Now create file “routes/main.js“:

module.exports = function(app) {
    app.get('/', (req, res) => {
        res.end('main');
    });
}

And the last – in file “app.js” require our routes – before app.listen insert this command: require(“./routes”)(app);

const express = require("express");
const app = express();
const port = 8000;

require("./routes")(app); // require /routes/index.js 

app.listen(port, () => {
    console.log("Server work on "+port); 
});

Start program in development mode:

npm run dev

Run Web-browser and open http://localhost:8000:

Similarly you can create /about, /contact or any other route on your NodeJS Web-site.