Tuesday, March 14

NodeJS Static Web Server


Introduction

The minimum amount of code to have NodeJS serve a static website.



Requirements

This code uses NodeJS module "express" which you install with the following command:
npm install express


Source Code

var Express = require('express')

  , app = Express()
 , http = require('http').Server( app )

 , htmlFolder = __dirname + '/html'
 , port = 2017
 ;

app.use(  Express.static( htmlFolder ) );


http.listen( port, function() {
 console.log( 'listening on *: ' + port );
 console.log( 'serving: ' + htmlFolder )
});


NodeJS Exit on Keypress


Introduction
This is an example of how easy it is to exit a NodeJS application by pressing a key. This code also will terminate the NodeJS application if the system sends it a "SIGTERM" command.

Example Code

/*
*  Exit handler
*/

function exit() {
 console.log('\n--App Exit--');
 process.exit();
}  

process.on('SIGTERM', exit );
/*
*  Handle Keypress
*/
process.stdin.setRawMode(true);
process.stdin.resume();
process.stdin.on('data', exit );

Java Script ES6 Custom Classes


Introduction

Most languages have support for objects. JavaScript has had support for objects for a long time, but now thanks to version ES6 we now have support for making custom classes. Below is example code of how easy it is to achieve this.

Example Code


class ClassName {

   constructor() {

       // Initialization Code
       this.variable = 'value';

   }

}


class SubClass extends ClassName

   constructor() {

       // Call parent’s constructor method
       super();

       // Initialization Code
       this.variable = 'value';

   }

}