introduction to node.js
TRANSCRIPT
INTRODUCTION TO NODE.JS
Md Sohel Rana
About MeMd. Sohel RanaFounder, NerdDevshttp://www.nerddevs.comtwitter : @sohel023010skype : sohel023010https://github.com/sohel-rana
What is Node.js A runtime
environment to support JavaScript as server side language
Built on V8-JavaScript Engine of Chrome
Event-driven, non-blocking I/O
Node.js Advantages
- Asynchronous I/O, more requests can serve- JavaScript as a Server Side language- Event Driven- A good package manager “NPM”
Disadvantages- Single threaded- Long processing unit can lock down the whole system
- Not elegant when more levels of callbacks
Hello World! Open your favorite text editor and write, console.log(‘Hello, World!’); Save the file as hello_world.js In terminal type node hello_world.js and
you should see this output
Node.js is asynchronous Every I/O operation needs a callback//reading host filevar fs = require('fs')
fs.readFile('/etc/hosts', 'utf8', function (err, data) { if (err) { return console.log(err); } console.log(data);});
Callback
Web ServerAn http server : var http = require('http');
http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n');}).listen(9000, '127.0.0.1');console.log('Server running at http://127.0.0.1:9000/');
Node Modules A functional unit
that performs specified actions
Loaded using require(‘module_name’)
Reusability
Node ModulesA simple module :
// “modules/calculator.js”exports.add = function(a, b){ return a+b ;};
exports.subtract = function(a, b){ return a-b;};
var Calculator = require('./module/calculator.js');var addTwoNumber = Calculator.add(5,7);
console.log(addTwoNumber); // will print 12
NPM NPM- node.js
package manager Used to
install/uninstall node programs
Can be used to install dependencies
package.json is used to define dependencies
//pakage.json{ "name": "backbone-express-boilerplate", "version": "1.0.0", "scripts": { "start": "node ./server/bin/www" }, "dependencies": { "express": "^4.12.3", "jade": "~1.9.2” }, "repository": { "type": "git", "url": "https://<repo-url.>git" }, "author": "Sohel Rana”, "bugs": { "url": "https://<repo-url>/issues" }, "homepage": "https://<repo-homepage>"}
Supporting Databases Has support for
almost every database
SQL-Server, MySQL, PostgreSQL, Oracle
Very often used with MongoDB
Connecting with DB Install a driver(node_module) for the DB Import that module using require For MongoDB, we can use Mongoose
Connect with MongoDBvar mongoose = require('mongoose');
mongoose.connection.on('open', function (ref) { console.log('Connected to mongo server.'); //do something here});mongoose.connection.on('error', function (err) { console.log('Could not connect to mongo server!'); console.log(err);});
mongoose.connect('mongodb://localhost/mydb');
Web Frameworks NodeJS provides
core modules Requires lots of
effort for web apps Express, Sails etc.
provides lots of feature top of it
Makes the maintenance easy
ExpressJS A complete web framework with routing Built-in REST API support Building API is quick and easy For installing, $npm install express --
save
Express web app var express = require('express');var app = express();
app.get('/', function (req, res) { res.send('Hello World!');});
var server = app.listen(3000, function () { var host = server.address().address; var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);});
Express web app Running the app will show this
If we visit http://localhost:3000 from browser, we will see
Express web app Show some html
var express = require('express’);
var app = express();
app.use('/public', express.static('public'));app.get('/', function (req, res) { res.sendFile(__dirname + '/index.html');});
var server = app.listen(3000, function () { var host = server.address().address; var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);});
Express web app
REST API An architectural style of building web
services Uses http verbs GET, POST, PUT, DELETE Not a Protocol like SOAP
REST API in Express app.get(), app.post(), app.put(),
app.delete() Some Examplesapp.get('/user/:id', function(req, res){ res.send('user ' + req.params.id);});
app.post('/save_user', function (req, res) { //save user data});
Hosting So many Cloud Platforms available Nodejitsu, appfog, Heroku, OpenShift NodeChef, EvenNode Microsoft Azure
Who are using
Future Getting popular for programming in IoT IBM, Microsoft investing Giant companies are using it NodeJS Foundation
Question?