Nodejs as a Web Server

Install ‘npm’ and ‘nodejs’:

$ sudo apt install nodejs
$ sudo apt install npm

Create a directory and add in index.html file:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
          <title>Mastering Web3 with Waves boilerplate</title>
          <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  </head>
  <body>
    <h1 class="display-3 text-center text-info">Hello Waves!</h1>
  </body>
</html>

Add a package.json file (think Gemfile). Express is the web server:

{
"name": "hello-node-js",
"version": "0.1.0",
"dependencies": {
"express": "^4.16.4"
}
}

Install the dependesncies:

$ npm install

Create a server.js to serve the file:

const express = require('express')
const app = express()
const port = process.env.PORT || 9999
const fileName = 'index.html'
app.get('/', (req, res) => {
  const options = {
    root: __dirname,
    dotfiles: 'deny',
    headers: {
      'x-timestamp': Date.now(),
      'x-sent': true
    }
  }
  res.sendFile(fileName, options, function (err) {
    if (err) {
      next(err)
    } else {
      console.log('Sent:', fileName)
    }
  })
})

app.listen(port, () => {
    console.log(__dirname);
    console.log("Listen: " + port);
})

Now run it:

jgriffiths@cynical:~/git/myTestServer$ node server.js
/home/jgriffiths/git/myTestServer
Listen: 9999

Leave a Reply

Your email address will not be published. Required fields are marked *