Nodejs at A Glance
Nodejs at A Glance
js
At a glance
Node.js at a glance - agenda
• Async Read/Write
• Sync Read/Write
• Node.js Network call (“net”)
• Node.js modules
• Web – Node.js (“http”)
• Web – Node.js (“express”) (html form with get/post)
• Web – Node.js (“express”) (routing)
• Web – Node.js (“express”) (middleware)
• Web – Node.js (“express”) (router)
Node.js – fs (Async Read)
var fs = require('fs');
var in_data;
console.log('Program Ended.');
Node.js – fs (Async Write)
var fs = require('fs');
var out_data = 'Output line 1.\r\nOutput line 2.\r\nOutput last line.';
console.log('Program Ended.');
Node.js – fs (Sync Read)
var fs = require('fs');
console.log('Program Ended.');
Node.js – fs (Sync Write)
var fs = require('fs');
var out_data = 'Output line 1.\r\nOutput line 2.\r\nOutput last line.';
fs.writeFileSync('./sync_output.txt', out_data);
console.log('Sync output file content: ' + out_data);
console.log('Program Ended.');
Node.js – net (Network Server)
var net = require("net");
var server = net.createServer(function(connection) {
console.log('Client connected.');
connection.on('end', function() {
console.log('Client disconnected.');
});
connection.write('Hello World!\n');
connection.pipe(connection);
// send data back to connection object which is client
});
server.listen(8080, function() {
console.log('Server is listening.');
});
console.log('Server Program Ended.');
Node.js – net (Network Client)
var client = net.connect({port: 8080}, 'localhost', function() {
console.log('Connected to Server.');
});
client.on('end', function () {
console.log('Disconnected from server.');
});
console.log('Client Program Ended.');
Node.js (Modules)
Module name Description
buffer buffer module can be used to create Buffer class.
console console module is used to print information on stdout
and stderr.
dns dns module is used to do actual DNS lookup and
underlying o/s name resolution functionalities.
domain domain module provides way to handle multiple
different I/O operations as a single group.
fs fs module is used for File I/O.
net net module provides servers and clients as streams.
Acts as a network wrapper.
os os module provides basic o/s related utility functions.
path path module provides utilities for handling and
transforming file paths.
process process module is used to get information on current
process.
Node.js – web module
• Web server is a software application which processes request using
HTTP protocol and returns web pages as response to the clients.
• Web server usually delivers html documents along with images, style
sheets and scripts.
• Most web server also support server side scripts using scripting
language or redirect to application server which perform the specific
task of getting data from database, perform complex logic etc. Web
server then returns the output of the application server to client.
• Apache web server is one of the most common web server being
used. It is an open source project.
Web server and Path
• Web server maps the path of a file using URL, Uniform Resource
Locator. It can be a local file system or a external/internal program.
• A client makes a request using browser, URL:
http://www.abc.com/dir/index.html
• Browser will make request as:
console.log('End of program');
Basic Routing
• Routing refers to determining how an application responds to a client request to a
particular endpoint, which is a URI (or path) and a specific HTTP request method (GET,
POST, and so on).
• Each route can have one or more handler functions, which are executed when the route is
matched.
• Route definition takes the following structure:
app.METHOD(PATH, HANDLER);
• Where:
• app is an instance of express.
• METHOD is an HTTP request method, in lower case.
• PATH is a path on the server
• HANDLER is the function executed when the route is matched.
Route methods
• A route method is derived from one of the HTTP methods, and is attached to an instance of the express class.
• The following code is an example of routes that are defined for the GET and POST methods to the root of the app.
• GET method route:
app.get('/', function (req, res) {
res.send('Get request to the homepage');
});
• POST method route:
app.post('/', function (req, res) {
res.send('Post request to the hmoepage');
});
• There is a special routing method, app.all(), which is not derived from any HTTP method. This method is used for loading middleware functions at a path for all request
methods. In the following example, the handler will be executed for requests to “/secret” whether you are using GET, POST, PUT, DELETE, or any other HTTP request
method that is supported in the http module.
app.all('/secret', function (req, res, next) {
console.log('Accessing the secret section ...');
next(); // pass control to the next handler
});
Node.js - routing (hkbu_app_route.js)
var express = require('express');
var app = express();
/* router level middleware with no mount path, all requests to this router will first hit this
middleware */
router.use(function(req, res, next) {
var d = new Date();
console.log('Time: ', d.toString());
next();
});
Node.js (router – hkbu_app_router.js)
// a middleware sub-stack to handle root path
// (router should mount to /user/:id)
router.get('/', function (req, res) {
console.log('wrong format');
res.end('** Wrong Format ** use http://localhost:3000/user/28');
});
app.listen(3000, function () {
console.log('listening to http://127.0.0.1:3000/ or http://localhost:3000/');
});
Error-handling Middleware
• Define error-handling middleware functions in the same way as other middleware functions,
except with four arguments instead of three, specifically with the signature (err, req, res, next)):
app.use(function(err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
• NOTE: Error-handling middleware always takes four arguments. You must provide four
arguments to identify it as an error-handling middleware function. Even if you don’t need to use
the next object, you must specify it to maintain the signature. Otherwise, the next object will be
interpreted as regular middleware and will fail to handle errors.
• For details about error-handling middleware, see: Error handling.
Built-in Middleware
• Starting with version 4.x, Express no longer depends on Connect. With the exception
of express.static, all of the middleware functions that were previously included with
Express’ are now in separate modules. Please view the list of middleware functions.
• The only built-in middleware function in Express is express.static. This function is
based on serve-static, and is responsible for serving static assets such as HTML files,
images, and so on.
• The function signature is:
express.static(root, [options])
• The root argument specifies the root directory from which to serve static assets.
• For information on the options argument and more details on this middleware
function, see express.static.
Built-in Middleware 2
• Here is an example of using the express.static middleware function with an elaborate options object:
var options = { dotfiles: 'ignore',
etag: false,
extensions: ['htm', 'html'],
index: false, maxAge: '1d',
redirect: false,
setHeaders: function (res, path, stat) { res.set('x-timestamp', Date.now()); }
}
app.use(express.static('public', options));
• You can have more than one static directory per app:
app.use(express.static('public'));
app.use(express.static('uploads'));
app.use(express.static('files'));
• For more details about the serve-static function and its options, see: serve-static documentation.
Serving Static files in Express
• To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express.
• Pass the name of the directory that contains the static assets to the express.static middleware function to start serving the files
directly. For example, use the following code to serve images, CSS files, and JavaScript files in a directory named public: (See
app9.js)
app.use(express.static('public'));
• Now, you can load the files that are in the public directory:
http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html
• To use multiple static assets directories, call the express.static middleware function multiple times:
app.use(express.static('public'));
app.use(express.static('files'));
Serving Static files in Express 2
• Express looks up the files in the order in which you set the static directories with the express.static middleware function.
• To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by
the express.static function,specify a mount path for the static directory, as shown below:
app.use('/static', express.static('public'));
• Now, you can load the files that are in the public directory from the /static path prefix.
http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html
• However, the path that you provide to the express.static function is relative to the directory from where you launch
your node process. If you run the express app from another directory, it’s safer to use the absolute path of the directory that you
want to serve:
app.use('/static', express.static(__dirname + '/public'));
Third-party Middleware
• Use third-party middleware to add functionality to Express apps.
• Install the Node.js module for the required functionality, then load it in your app at the application level or at the
router level.
• The following example illustrates installing and loading the cookie-parsing middleware function cookie-parser.
$ npm install cookie-parser