Tag Archives: Node.js

How to include external libraries by requiring modules in node.js?

To include external libraries in Java, we use import statement.

In node.js, we use require keyword. For example,

var http = require(‘http’);

We can also include relative files as shown below:

var myFile = require(‘./myFile’); // loads myFile.js

To install modules from npm(node package manager),

$ npm install express

Modules aren’t automatically injected into the global scope, but instead you just assigned them to a variable of your choice.

 

You can create your own module as well.

  •  The first approach would be to export a single object:

        var person = { name: ‘John’, age: 20 };

        module.exports = person;

  • The second approach requires adding properties to the exports object:

     exports.name = ‘John';
       exports.age = 20;

Modules don’t share scope, so if you want to share a variable between different modules, you must include it into a separate module that is then required by the other modules. And also modules are loaded once and then are cached by node.


ProsperaSoft offers Node.js development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Node.js experts and consultants.

 

 

 

How to handle errors in Node.js?

Error Handling is important in any of the language. If you don’t handle errors, then your program may crash or go to inconsistent state.

In Node, we have Error-first callback as the  standard protocol for callbacks. This is very simple convention with only one rule, the first argument for the callback function should be the error object.

That is there are following two scenarios:

1. Your Error argument is null, then your program is without error.

2.  Your Error argument is not null, then you need to handle error.

Example of Error-first callback:

fs.readFile(‘/foo.txt’, function(err, data) {
// …
});

Here, readFile has two parameters error and file data.

To handle err, you just need to put a check for getting value of err.

If( err ){
console.log(err);
}else{
console.log(“working fine”);
}

EventEmitter errors:

When working with event emitters , you should be careful. If there’s an unhandled error event it will crash our application.

Example of eventEmitter:

var EventEmitter = require(‘events’).EventEmitter;
var emitter = new EventEmitter();
emitter.emit(‘error’, new Error(‘something bad happened’));

You can handle event emitter errors as shown below:

emitter.on(‘error’, function(err) { console.error(‘something went wrong with the ee:’ + err.message); });

Propagating more descriptive errors with the verror module:

There are some situations where we don’t handle errors ourselves. We just delegate it to callback.In above way of handling errors, we don’t get exact stack trace.

In real world applications, there will probably be a function that calls another function that calls the original function. So, to know from where exactly error came.

For this Node has verror module, which we have to integrate with the application.With verror, we can wrap our errors to provide more descriptive messages.

We will have to require the module at the beginning of the file and then wrap the error when invoking the callback:

var verror = require(‘verror’);
function readFiles(files, callback) { …
return callback(new VError(err, ‘failed to read file %s’, filePath));

}

 


ProsperaSoft offers Node.js development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Node.js experts and consultants.

 

 

How to access MySql database with Node?

In Node, everything goes with modules i.e., download and install module. For accessing MySql , we have module mysql@2.0.0-alpha2.

Steps to access MySql  with Node:

1. Install module:

npm install mysql@2.0.0-alpha2

This will download and install module for mysql.

2. Using module in your application:

var http = require(‘http’),
// And mysql module you’ve just installed.
mysql = require(“mysql”);

// Create the connection.
// Data is default to new mysql installation and should be changed according to your configuration.
var connection = mysql.createConnection({
user: “root”,
password: “”,
database: “db_name”
});

// Create the http server.
http.createServer(function (request, response) {
// Attach listener on end event.
request.on(‘end’, function () {
// Query the database.
connection.query(‘SELECT * FROM your_table;’, function (error, rows, fields) {
response.writeHead(200, {
‘Content-Type': ‘x-application/json’
});
// Send data as JSON string.
// Rows variable holds the result of the query.
response.end(JSON.stringify(rows));
});
});
// Listen on the 8080 port.
}).listen(8080);

Querying with this library is easy as we just need to write query and a callback function.

3. Save this file as mysql.js and run it as

$node mysql.js

4. Then navigate to http://localhost:8080 in your browser, and you should be prompted to download the JSON-formatted file.


ProsperaSoft offers Node.js development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Node.js experts and consultants.

 

How to read and write files in Node.js?

To manage files in Node, we use the fs module (a core module). We read and write files using the fs.readFile() and fs.writeFile() methods, respectively.

Steps to read and write files are shown below:

// Include http module,
var http = require(“http”),
fs = require(“fs”);

// Create the http server.

http.createServer(function (request, response) {
// Attach listener on end event.
request.on(‘end’, function () {
// Check if user requests /
if (request.url == ‘/’) {
// Read the file.
fs.readFile(‘test.txt’, ‘utf-8′, function (error, data) {
// Write headers.
response.writeHead(200, {
‘Content-Type': ‘text/plain’
});
// Increment the number obtained from file.
data = parseInt(data) + 1;
// Write incremented number to file.
fs.writeFile(‘test.txt’, data);
// End response with some nice message.
response.end(‘This page was refreshed ‘ + data + ‘ times!’);
});
} else {
// Indicate that requested file was not found.
response.writeHead(404);
// And end request without sending any data.
response.end();
}
});
// Listen on the 8080 port.
}).listen(8080);

This code demonstrates the fs.readFile() and fs.writeFile() methods. Every time the server receives a request, the script reads a number from the file, increments the number, and writes the new number to the file. The fs.readFile()method accepts three arguments: the name of file to read, the expected encoding, and the callback function.

Save this as files.js. Before you run this script, create a file named test.txt in the same directory as files.js.

Run application as $node file.js


ProsperaSoft offers Node.js development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Node.js experts and consultants.

 

Debugging Node applications

For debugging in Node, we have node-inspector module available.

To install node-inspector write following:

npm install -g node-inspector

To run your application with node-inspector,

# basically `node-debug` instead of `node`
$ node-debug example.js

where example.js is name of your application.

That should start our application and open the node-inspector interface in Chrome.  Then setup breakpoint in request handler click on line from where you want to start debugging code. Then visit to localhost in new tab.


ProsperaSoft offers Node.js development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Node.js experts and consultants.

 

Events in Node

Events lie at the heart of Node.js. In fact, events ARE the heart of Node.js. When building our own custom modules, we are able to make use of this functionality provided by Node.js for emitting our very own events. We can do this by using the EventEmitter exposed by the built-in ‘events’ module. The following code snippet demonstrates how to use the simple API of the EventEmitter.

var events = require(‘events’);
var eventEmitter = new events.EventEmitter();
eventEmitter.on(‘someOccurence’, function(message){
console.log(message);
});
eventEmitter.emit(‘someOccurence’, ‘Something happened!’);

After creating an eventEmitter object, we subscribe to an event named ‘someOccurence’ and register a function with a message argument to be called when the event is raised. Subscribing is done by executing the on() method of the eventEmitter object. Next we raise our event by simply calling the emit() method of the eventEmitter object, also passing in the value for the message argument of the event handler function.


ProsperaSoft offers Node.js development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Node.js experts and consultants.

 

How to create HTTP server in Node?

To create HTTP server in node, we have to include http module. As shown below:

var http = require(“http”);

// request variable holds all request parameters
// response variable allows you to do anything with response sent to the client.
http.createServer(function (request, response) {
// Attach listener on end event.
// This event is called when client sent all data and is waiting for response.
request.on(“end”, function () {
// Write headers to the response.
// 200 is HTTP status code (this one means success)
// Second parameter holds header fields in object
// We are sending plain text, so Content-Type should be text/plain
response.writeHead(200, {
‘Content-Type': ‘text/plain’
});
// Send data and end response.
response.end(‘Hello HTTP!’);
});
// Listen on the 8080 port.
}).listen(8080);

This code is very simple. You can send more data to the client by using theresponse.write() method, but you have to call it before calling response.end().

Now, save file as server.js and in your console write following:

$node server.js

Open up your browser and navigate to http://localhost:8080. You should see the text “Hello HTTP!” in the page.


ProsperaSoft offers Node.js development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Node.js experts and consultants.

 

File Uploads in Node.js

We will use Express Framework  and middleware called “multer”.  This middleware is designed for handling the multipart/form-data.

To install multer write following command:

$ npm install multer

To configure multer add following code in server.js:

app.use(multer({ dest: ‘./uploads/’,
rename: function (fieldname, filename) {
return filename+Date.now();
},
onFileUploadStart: function (file) {
console.log(file.originalname + ‘ is starting …’)
},
onFileUploadComplete: function (file) {
console.log(file.fieldname + ‘ uploaded to ‘ + file.path)
done=true;
}
}));

Multer emits event on particular situation such as we used onFileUploadStart which means when file start uploading, this event will be emitted.

As soon as onFileUploadComplete event emitted we have set the variable done to true and use it in our router to determine whether file is uploaded or not.

For handling routes, add following code in server.js:

app.get(‘/’,function(req,res){
res.sendfile(“index.html”);
});

app.post(‘/api/photo’,function(req,res){
if(done==true){
console.log(req.files);
res.end(“File uploaded.”);
}
});

To run server add following in server.js:

app.listen(3000,function(){
console.log(“Working on port 3000″);
});

Now, in your HTML file add following:

<form id = “uploadForm”
enctype = “multipart/form-data”
action = “/api/photo”
method = “post”
>
<input type=”file” name=”userPhoto” />
<input type=”submit” value=”Upload Image” name=”submit”>
</form>

In HTML form you must mention enctype=”multipart/form-data” else multer will not work.

Now run your project :

$ node server.js

And visit localhost:3000 to view running application.

To perform validation on Server end, multer provides limits array parameter. If you want you can perform validation as shown below:

app.use(multer({ dest: ‘./uploads/’,
rename: function (fieldname, filename) {
return filename+Date.now();
},
limits: {
fieldNameSize: 100,
files: 2,
fields: 5
}
}));

Multer provides easy way to upload files in Node.js.


ProsperaSoft offers Node.js development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Node.js experts and consultants.

 

How to send e-mail in Node.js?

In most of real time application we need to send mails for account verification, account recovery, etc. Hence, for Node applications also we need to find some way to send email.

For that Node already have nodemailer module which makes task very easy.

First of all, you will need to install nodemailer and express.js.

npm install nodemailer

npm install express

Then setup your server.js file.

var express=require(‘express’);
var nodemailer = require(“nodemailer”);
var app=express();
app.listen(3000,function(){
console.log(“Express Started on Port 3000″);
});

In your HTML file, you will need add code to hit server.js to send mail. Hence, add following code to your HTML file.

$(document).ready(function(){
var from,to,subject,text;
$(“#send_email”).click(function(){  // send_email is id of button 
to=$(“#to”).val();
subject=$(“#subject”).val();
text=$(“#content”).val();
$(“#message”).text(“Sending E-mail…Please wait”);
$.get(“http://localhost:3000/send”,{to:to,subject:subject,text:text},function(data){
if(data==”sent”)
{
$(“#message”).empty().html(“Email is been sent at “+to+” . Please check inbox !”);

}});

});

});

As we are making request to server we need to handle this in server side also.

app.get(‘/send’,function(req,res){
//code to send e-mail.
});

Now, add nodemailer code,

var smtpTransport = nodemailer.createTransport(“SMTP”,{
service: “Gmail”,
auth: {
user: “yourID@gmail.com”,
pass: “Your Gmail Password”
}
});

Add above code in server.js ,

var smtpTransport = nodemailer.createTransport(“SMTP”,{
service: “Gmail”,
auth: {
user: “yourID@gmail.com”,
pass: “Your G-mail password”
}
});

app.get(‘/’,function(req,res){
res.sendfile(‘index.html’);
});
app.get(‘/send’,function(req,res){
var mailOptions={
to : req.query.to,
subject : req.query.subject,
text : req.query.text
}
console.log(mailOptions);
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
res.end(“error”);
}else{
console.log(“Message sent: “ + response.message);
res.end(“sent”);
}
});
});


ProsperaSoft offers Node.js development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Node.js experts and consultants.

 

 

How to do String validation in Node.js?

In all real time application we need to use validation so that proper data is been entered by user. Lets see how we can do it in Node.js:

Node.js provides ‘validator‘ library to do validation. To install validator do following:

npm install validator

This package covers most of the string sanitization and validation.

For example, isEmail(), isURL(), isIP(), etc.

On server side you need to check validation as shown below:

var validator = require(validator);
validator.isEmail(mail_id _from_params); 
On client side do following:
Add <script type=”text/javascript” src=”validator.min.js”></script>
validator.isEmail(foo@bar.com); // return true

ProsperaSoft offers Node.js development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Node.js experts and consultants.