In this section, our plan is to lead you into the world of Nodejs programming by taking you through the two basic steps required to get a simple program running. As with any application, you need to be sure that Nodejs[1] is properly installed on your computer. You also need an editor (I will suggest sublime[2] editor) and a terminal application.
Programming in Nodejs.
We break the process of programming in Nodejs into two steps:
Executing a Nodejs program. This is the exciting part, where the node follows your instructions.
To run the file reading program, type the following at the terminal:
If all goes well, you should see the following response
Understanding NodeJs Program:
In this program, we read the resource.json file from disk. When all the data is read, anonymous function is called (a.k.a. the “callback”) containing the arguments error, if any error occurred, and data , which is the file data.
Programming in Nodejs.
We break the process of programming in Nodejs into two steps:
- Create the program by typing it into a text editor and saving it to a file named, say, app.js.
- Run (or execute) it by typing "node app.js" in the terminal window.
//app.js
var fs = require('fs');
fs.readFile('./resource.json', function (error, data) {
if(error){
console.log("erro while reading resource.json file"+error);
}
console.log(data);
});
//resource.json
{
"additionalFeatures": "Contour Display, Near Field Communications (NFC), Three-axis gyroscope, " +
"Anti-fingerprint display coating, Internet Calling support (VoIP/SIP)",
"android": {
"os": "Android 2.3",
"ui": "Android"
},
"availability": [
"M1,",
"O2,",
"Orange,",
"Singtel,",
"StarHub,",
"T-Mobile,",
"Vodafone"
],
"battery": {
"standbyTime": "428 hours",
"talkTime": "6 hours",
"type": "Lithium Ion (Li-Ion) (1500 mAH)"
}
}
Executing a Nodejs program. This is the exciting part, where the node follows your instructions.
To run the file reading program, type the following at the terminal:
$ node app.js
If all goes well, you should see the following response
{
"additionalFeatures": "Contour Display, Near Field Communications (NFC), Three-axis gyroscope, " +
"Anti-fingerprint display coating, Internet Calling support (VoIP/SIP)",
"android": {
"os": "Android 2.3",
"ui": "Android"
},
"availability": [
"M1,",
"O2,",
"Orange,",
"Singtel,",
"StarHub,",
"T-Mobile,",
"Vodafone"
],
"battery": {
"standbyTime": "428 hours",
"talkTime": "6 hours",
"type": "Lithium Ion (Li-Ion) (1500 mAH)"
}
}
Understanding NodeJs Program:
In this program, we read the resource.json file from disk. When all the data is read, anonymous function is called (a.k.a. the “callback”) containing the arguments error, if any error occurred, and data , which is the file data.
Comments
Post a Comment