Node.js is a javascript based server side scripting platform just like php, python or ruby.
Php depends on Apache or nginx web servers for handling http request and response, on the other hand,Node.js has its own http server library allowing us to have more control over the web server.
Node.js is built on Chrome's JavaScript runtime V8 for developing fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.
An application is said to be scalable when it is efficient and practical when applied to large situations(eg: large input data set, a large number of outputs or users). If the application fails when quantity increases, it is not scalable.
When you are using a traditional web server like Apache, when a request is received, it processes that request and goes to next request. if that request takes time, the server will wait for it and then moves to the next request. In order to process more requests, the web server uses multiple threads-which is more resource consuming.
In event-driven or non-blocking I/O model the web server accepts the request, then goes back to service next web request(it does not block that I/O operation). When the original request is completed, it comes back in the processing queue and then the results are sent to the browser. This makes it highly efficient and scalable. This is what made nginx webserver very popular. nginx uses a scalable event-driven (asynchronous) architecture. The same technology is used in node.js in a much efficient way.
To Handle 10,000 simultaneous requests node.js uses a few MB of RAM whereas Apache would probably consume hundreds of MB.
Benchmark-
100 concurrent clients
1 megabyte response
node.js-> 822 requests/sec
nginx-> 708 requests/sec
thin-> 85 requests/sec
mongrel-> 4 requests/sec
(bigger is better)
eBay, Microsoft, Yahoo!, StrongLoop, OmniTI, Storify, local response, nodejitsu, Linkedin, Iris Couch, backbeam, recruitics, Transloadit, Uber, Voxer,when-to-manage, Jaleoo, Cloud9 IDE, NODE the FIRM etc..
Asynchronous- Asynchronous means an event which is happening independently of other events. The main advantage of the asynchronous approach is scalability.
Npm- Stands for node package manager. This will help us install the latest modules directly from the servers instead of checking for the latest version, downloading and copying to the appropriate directory. It also has other uses.
Express- Express is a highly recommended web application framework for node.js. It takes care of the low-level services for us.
Module- A module is an independent, reusable piece of code. you can download them and use them directly in your project. ex: express, http, https etc are some of the modules for node.js.
REPL-Read-Eval-Print-Loop provides a way to interact with javascript it can be used for debugging, testing. To try repl go to terminal(cmd prompt) and type node and try ex: console.log("learn nodejs");
Mongoose- Mongoose is a MongoDB object modeling tool for node.js. It becomes easy to interact with MongoDB database server using Mongoose module.
Db-mysql- It is a node.js module to interact with MySQL database.
Note
If you have any problems during Linux installation please make sure you have python and OpenSSL installed.
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('First node.js example');
}).listen(8123);
console.log('Server running at http://localhost:8123/');
->goto->cmd prompt->enter the directory where u saved the file->type in node nodeexample.js(u ll get: server running at 127.0.0.1:8123).
->then open browser and type->http://localhost:8124
->output-> First node.js example
->use ctrl+c to stop the server.
line1->when ever we are using any modules(built-in or external), we have to include them first.
line2->http.createServer will return a new web server object. we have to create a server object to use http server.
line3->sends a response to the browser. You can also use response.write() method. these must be used only before response.end() method.
line4->listens to the port. You can send an optional parameter of 'localhost'.
line5->console.log() will output to the console and not the browser window.
Note- Whenever you modify the file, don't forget to restart the server ie., stop the server using ctrl+c and run the file again.
var http = require('http');
var fs = require('fs');
http.createServer(function (request, response) {
fs.readFile('index.html','utf8', function (err, data) {
if (err){
response.write('unable to load the requested file');}
else{
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data);
}
response.end();
});
}).listen(8123);
console.log('Server running at http://localhost:8123/');
->now run the file to start the server.
->goto->http://localhost:8123.
->the output will be the contents of the file.
line2-> We have included filesystem module. Using this module we will be able to access the file system.This is builtin module no need to download it.
line4-> readFile() function is used to read the files from the disk. function(err, data) is the callback function and it is mandatory.what happens here is node.js will not wait for the response and will carry on with the execution and when the response is ready it will be outputted.
line5-> If there is an error reading the file there will be one response. If everything ok then else part is executed. here 'data' stores the contents of your file we can change the name, and make sure that index.html exists in your current directory.
Email is the electronic version of the traditional mail. Email is fast, secure, reliable and widely used by millions of people in today’s world.
E-mail is used for the variety of different situations such as newsletters, contact forms, formal Communication, informal communication and many more. E-mail helps businesses to expand their customer base by sending new offers, newsletters and customer support communication.
Businesses use newsletters to update their customer about their new products and services, thereby driving web traffic to their site.
There are many different protocols in which we can send emails the most widely used protocols are IMAP, POP3, SMTP, HTTP and many more like Amazon SES. Keep a note of the port which is useful for sending and receiving emails through our code.
npm install express –g
npm install jade –g
npm install nodemailer –g
express email (project name)
cd email
npm link express
npm link jade
npm link nodemailer
node app.js //to run the app
And go to your favorite browser (any browser) and type “localhost:3000″ in the address bar and press enter. If you get the “welcome to express” page you have successfully created an app in node.js using express.
Open index.jade file inside /view folder and replace it with following code.
extends layout
block content
form(action='/contact', name='contactus', id='contactus', method='post')
p
label(for='name') Name:
br
input(name='name', type='text', value='', id='name')
p
label(for='email') Email:
br
input(name='email', type='text', value='', id='email')
p
label(for='message') Message:
br
textarea(name='message', cols='40', rows='10', id='message')
p
input(name='submit', type='submit', value='Send', id='submit')
Open app.js file inside the email folder and replace it with following code.
/**
Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
//include the nodemailer module
var nodemailer = require('nodemailer');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
app.post('/contact', function (req, res) {
var mailOpts, smtpConfig;
smtpConfig = nodemailer.createTransport('SMTP', {
service: 'Gmail',
auth: {
user: "[email protected]",
pass: "yourpasswordhere"
}
});
//construct the email sending module
mailOpts = {
from: req.body.name + ' <' + req.body.email + '>',
to: ' yourGmailidGoesHere @gmail.com',
//replace it with id you want to send multiple must be separated by ,(comma)
subject: 'contact form',
text: req.body.message
};
//send Email
smtpConfig.sendMail(mailOpts, function (error, response) {
//Email not sent
if (error) {
res.end("Email send Falied");
}
//email sent successfully
else {
res.end("Email sent successfully");
}
});
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
//include the nodemailer module
var nodemailer = require('nodemailer');
This code simply loads nodemailer module and this is the first step.
app.post('/contact', function (req, res) {
var mailOpts, smtpConfig;
smtpConfig = nodemailer.createTransport('SMTP', {
service: 'Gmail',
auth: {
user: " yourGmailidGoesHere @gmail.com",
pass: "yourpasswordgoeshere"
}
});
//construct the email sending module
mailOpts = {
from: req.body.name + ' <' + req.body.email + '>',
to: '[email protected]',
//replace it with id you want to send multiple must be separated by , (Comma)
subject: 'contact form',
text: req.body.message
};
//send Email
smtpConfig.sendMail(mailOpts, function (error, response) {
//Email not sent
if (error) {
res.end("Email send Falied");
}
//email send sucessfully
else {
res.end("Email send sucessfully");
}
});
});
This is our email sending module where “var mailOpts, smtpConfig” are the two objects which store our SMTP configuration and mail sending options.
smtpConfig = nodemailer.createTransport('SMTP', {
service: 'Gmail',
auth: {
user: "[email protected]",
pass: "yourpasswordgoeshere"
}
});
Here we store the Gmail email id and password which will be passed to every sent mail. When nodemailer calls Gmail, it passes this information and Gmail will authenticate and then only sends an email. So it is important that we should have an active Gmail email id and password for this module to work.
mailOpts = {
from: req.body.name + ' <' + req.body.email + '>',
to: '[email protected]', //replace it with id you want to send multiple must be separated by ,
subject: 'contact form',
text: req.body.message
};
Here we store from, to, subject and the message that need to be send. We can send email to multiple ids by simply separating email address with comma.
smtpConfig.sendMail(mailOpts, function (error, response) {
//Email not sent
if (error) {
res.end("Email send Falied");
}
//email send sucessfully
else {
res.end("Email send sucessfully");
}
});
This is the most important code. Here we send the actual email and pass all the required email header information such as to, from, message using the mailOpts object with the emailid and password used to send this email.
We have used the free Gmail SMTP and nodemailer Email module to send emails in node.js since Gmail is a widely used email service provider. We can use other email providers such as Yahoo, Zoho etc. nodemailer also supports XOAUTH2 authentication protocol. To use this you need to obtain a Client ID and a Client Secret from Google API Console.
There are other email sending modules such as simplesmtp, IMAP, SMTP-protocol, etc… But nodemailer is widely used, supports most of the features, easy to implement and support windows.
I hope this tutorial added some value to you. I am more than happy and found it all fun putting this together just for you. I wish to do more and I will.
Thanks for your time.