Share via


Setting up a node.js website in Visual Studio Code

Node.js is a cross platform environment for hosting JavaScript. It is ideal for network and I/O based applications.

Install node.js from https://nodejs.org/

The components for node is shown below:

V8:  It is a JavaScript runtime built and maintained by Google

Node: A wrapper that provide API for the client application to access server resource and also run JavaScript on server

NPM: Package manager similar to NuGet

  • Open a folder in Visual Studio Code as shown

  • Install Express : It is a "minimal and flexible node.js web application framework 

  • npm install express
    
  • Install view engine : We will use the handlebars view engine 

    npm install hbs
    

 

  • The folder structure in visual studio code is updated as shown 

  • Add the new files and folder as shown

  • Update the home.hbs with the below HTML
<h1> First Node Project test </h1>
  • Update the server.js with the below code
'use strict'
var http = require('http');
var express = require('express');
var expressHandlebars = require('hbs');

// setup express
var app = express();

// configure handlebars as the view engine
expressHandlebars.registerPartials(__dirname + '/views');

// configure express to use handlebars as the view engine
app.set('view engine', 'hbs');
// change express default where to look for views on the server
app.set('views', __dirname + '/views');

var httpServerPort = process.env.PORT || 3000;  // use server value (for Azure) or local port

// create & startup HTTP webserver
http.createServer(app)
    .listen(httpServerPort);

console.log('+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+');
console.log('Web Server listening at http://localhost:%s', httpServerPort);
console.log('+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+');


app.get('/', function (req, res) {
  res.render('home',
  { title : 'Home' }
  )
})
  • Navigate to the folder which contains the server.js and run the node server as shown.

  • Navigate to the folder which contains the server.js and run the node server as shown.