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

First create file app.js:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const express = require("express");
const app = express();
const port = 8000;
app.listen(port, () => {
console.log("Server work on "+port);
});
const express = require("express"); const app = express(); const port = 8000; app.listen(port, () => { console.log("Server work on "+port); });
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const mainRoutes = require('./main');
module.exports = function(app) {
mainRoutes(app);
}
const mainRoutes = require('./main'); module.exports = function(app) { mainRoutes(app); }
const mainRoutes = require('./main');

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

Now create file “routes/main.js“:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
module.exports = function(app) {
app.get('/', (req, res) => {
res.end('main');
});
}
module.exports = function(app) { app.get('/', (req, res) => { res.end('main'); }); }
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);

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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);
});
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); });
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.