ExpressJS Snippets

1)
If next is called then it function will not return after execution of request.

app.get(/dishes/:dishId, function(req, res, next) {
res.end(‘sending it to server’+ req.params.dishId);
});

2)
Get the request data
req.body.name; req.body.description

3)
res.write();
res.end();

4) Express Routers

var dishRouter = express.Router();dishRouter.use(bodyParser.json());

dishRouter.route(‘/’)
.all(function(req,res,next){
res.writeHead(200, {‘Content-type’:’text/plain’});
next();
})
.get(function(req,res, next) {
res.end(‘retrieving the request’);
});

app.use(‘/dishes’, dishRouter);

NodeJS/ExpressJS Middlewares

NodeJS/ExpressJS Middleware:

The order in which middleware are defined in a file tells the order in which they would be applied to an incoming request.

To install a middleware :: npm install middleware-name –save

1) morgan for logging.
app.use(morgan(‘dev’));

2) express.static for serving static content
app.use(express.static(__dirname + ‘/public’));

Static files requested can only be sent using the GET request not the POST request. Create a folder named ‘public’ with the static content inside.

3) body-parser for parsing the json or other content in body of request

eg. var bodyParser = require(‘body-parser’);
app.use(bodyParser.json());

4) Express Generator: Quick scaffolding tool to generate an Express application skeleton.
npm install express-generator -g

Go into the folder in which you want to create the node express application skeleton:
express app-name (generates the application skeleton).

Now install the dependencies from package.json
npm install

Now you can start the express server with :
npm start

Express Generator: http://expressjs.com/en/starter/generator.html

 

Using MongoDB with NodeJS

http://blog.modulus.io/mongodb-tutorial

Install modules:
npm install mongodb –save
npm install assert –save

var MongoClient = require('mongodb').MongoClient,
assert = require('assert');

// Connection URL
var url = 'mongodb://localhost:27017/conFusion';

// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {

    assert.equal(err,null);
    console.log("Connected correctly to server");
	
	var collection = db.collection("dishes");
	collection.insertOne({name: "Uthapizza", description: "test"}, function(err,result){
		assert.equal(err,null);
		console.log("After Insert:");
		console.log(result.ops);
			collection.find({}).toArray(function(err,docs){
				assert.equal(err,null);
				console.log("Found:");
				console.log(docs);
				db.dropCollection("dishes", function(err, result){
				   assert.equal(err,null);
				   db.close();
				});
			});
	});
});

Nods.js Basics

CommonJS Module format

Each file in a node is its own module.

The require function is used to import a module. (eg. require(‘./abc’))

 

Installing external yargs node module to take command line args

npm install yargs –save  (to save dependencies in package.json file)

 

Postman chrome extension for viewing the http request and response messages

nodejs ht

 

FileSystem Module:

Non Blocking call to read a file

var fs = require("fs");

fs.readFile('input.txt', function (err, data) {
if (err) return console.error(err);
console.log(data.toString());
});

Blocking call to read a file

var fs = require("fs"); 
var data = fs.readFileSync('input.txt');
console.log(data.toString());

 

Events Module:

// Import events module
var events = require('events');

// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();

// Bind event and even handler as follows
eventEmitter.on('eventName', eventHandler);

// Fire an event 
eventEmitter.emit('eventName');

====================================================================
Streams
Streams are objects that let you read data from a source or write data to a destination in continous fashion. In Node.js, there are four types of streams.
Readable, Writable, Duplex, Transform.

Each type of Stream is an EventEmitter instance and throws several events at different instance of times.

Events thrown by the streams.
data, end, error, finish.

Read Stream Example

var fs = require("fs");
var data = '';

// Create a readable stream
var readerStream = fs.createReadStream('input.txt');

// Set the encoding to be utf8. 
readerStream.setEncoding('UTF8');

// Handle stream events --> data, end, and error
readerStream.on('data', function(chunk) {
   data += chunk;
});
readerStream.on('end',function(){
   console.log(data);
});
readerStream.on('error', function(err){
   console.log(err.stack);
});
console.log("Program Ended");

Write stream example

var fs = require("fs");
var data = 'Simply Easy Learning';

// Create a writable stream
var writerStream = fs.createWriteStream('output.txt');

// Write the data to stream with encoding to be utf8
writerStream.write(data,'UTF8');

// Mark the end of file
writerStream.end();

// Handle stream events --> finish, and error
writerStream.on('finish', function() {
    console.log("Write completed.");
});
writerStream.on('error', function(err){
   console.log(err.stack);
});
console.log("Program Ended");

Piping Streams
Piping is a mechanism where we provide output of one stream as the input to another stream. It is normally used to get data from one stream and to pass output of that stream to another stream. There is no limit on piping operations.

var fs = require("fs");

// Create a readable stream
var readerStream = fs.createReadStream('input.txt');

// Create a writable stream
var writerStream = fs.createWriteStream('output.txt');

// Pipe the read and write operations
// read input.txt and write data to output.txt
readerStream.pipe(writerStream);

console.log("Program Ended");

Chaining StreamsChanining is a mechanism to connect output of one stream to another stream and create a chain of multiple stream operations. It is normally used with piping operations.

var fs = require("fs");
var zlib = require('zlib');

// Compress the file input.txt to input.txt.gz
fs.createReadStream('input.txt')
  .pipe(zlib.createGzip())
  .pipe(fs.createWriteStream('input.txt.gz'));
  
console.log("File Compressed.");

===============================================================
Buffer Module:

Buffer class provides instances to store raw data similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap.

Buffer class is a global class and can be accessed in application without importing buffer module.


Node Buffer can be constructed in a variety of ways.

1) var buf = new Buffer(10);
2) var buf = new Buffer([10, 20, 30, 40, 50]);
3) var buf = new Buffer("Simply Easy Learning", "utf-8");


To write into a Node Buffer:
  write returns the number of bytes written

buf = new Buffer(256);
len = buf.write("Simply Easy Learning");
console.log("Octets written : "+  len);


To convert a Node Buffer into JSON object:
Returns a JSON-representation of the Buffer instance.
buf.toJSON()

Concatenation:  Buffer.concat([buffer1,buffer2]);

Compare Buffers : buffer1.compare(buffer2);

Copy Buffers: buffer1.copy(buffer2);

Buffer length: buffer.length;

Slice Buffer: buffer.slice(0,9);

===============================================================

Global Objects: Node.js global objects are global in nature we do not need to include these objects in our application, rather we can use them directly.
These objects are modules, functions, strings and object itself.

__filename
The __filename represents the filename of the code being executed. This is the resolved absolute path of this code file
console.log( __filename );
__dirname
The __dirname represents the name of the directory that the currently executing script resides in.
console.log( __dirname );
Console:console is a global object and is used to print different levels of messages to stdout and stderr. There are built-in methods to be used for printing informational, warning and error messages.

It is used in synchronous way when destination is file or a terminal and asynchronous way when destination is a pipe.

eg.
console.info("Program Started");
var counter = 10;
console.log("Counter: %d", counter);

console.time("Getting data");

 

Process: The process object is a global object and can be accessed from anywhere. There are number of useful methods available through a process object.

The process object is an instance of EventEmitter and emits following events:

exit, beforeExit, uncaughtException, Signal Events

Process object also provides many useful properties and method reference.

 

Global Functions:

setTimeout(cb, ms)
The setTimeout(cb, ms) global function is used to run callback cb after at least ms milliseconds.
This function returns an opaque value that represents the timer which can be used to clear the timer.
clearTimeout(t):Global function is used to stop a timer that was previously created with setTimeout().
setInterval(cb, ms)The setInterval(cb, ms) global function is used to run callback cb repeatedly after at least ms milliseconds.
clearInterval(t): Is used to clear an interval.

 

================================================================================
Web Module

var http = require('http');
// creating server
http.createServer(......);
http.listen(port_no);

// creating client
var options = {
   host: 'localhost',
   port: '8081',
   path: '/index.htm'  
};

var req = http.request(options, callback);
req.end();

===============================================================================
Callback functions: In Node Application, any async function accepts a callback as a last parameter and the callback function accepts error as a first parameter.