Node.js is a
powerful framework developed on Chrome’s V8 JavaScript engine
Node JS is an open
source server environment for java script, you can run you java script in
server using Node JS, earlier
To run you first Node JS
programe create a folder under user directory
C:\Users\<SysUserName>\<Node
Folder any Name>\<place here all js files>
Now open command prompt and
navigate to above directory
Open notepad and write the
below code –
var http = require('http');
http.createServer(function
(req, res) {
res.writeHead(200, {'Content-Type':
'text/html'});
res.end('Welcome in MK Study Journal!');
}).listen(8080);
Save the file <filename>.js extension and
run below command on CMD.
Node <fileName>.js
This will print “Welcome in MK Study Journal” in
browser.
Let’s explain above code
var http = require('http'); it’s importing the http module, there are
several module that can be import as per requirement.
You can also download other module using npm(node
package manager), use below command –
npm
install <package-name>
createServer is callback function in http
module, it have 2 argument req and res, in res field we specify the header with
status code and content-type, ending with string “Welcome in MK Study Journal”
In above example we are using built in module
http.
To use a module use require(“<module-name>”)
List of built in module-
1.
http- This is used for http server, http request
and http response object
2.
url- Is used for url parsing, fetching details
like hostname, port etc
3.
querystring- method to handle querystring
4.
path- File path methods
5.
fs- Used for file i/o operation
6.
util- Used for utils functions
Refer below example for few of built in
modules.
var url = require('url');
var urladdress =
'http://localhost:8080/default.htm?query1=test1&query2=test2';
var parsedurl =
url.parse(urladdress, true);
console.log(parsedurl.host);
console.log(parsedurl.pathname);
console.log(parsedurl.search);
var querydata =
parsedurl.query;
console.log(querydata.query1);
var http = require('http');
var fs = require('fs');
http.createServer(function
(req, res) {
fs.writeFile('mkstudyjournal.txt', 'hello !
welcome!', function(err) {
res.writeHead(200, {'Content-Type':
'text/html'});
});
fs.readFile('mkstudyjournal.txt',
function(err, data) {
res.writeHead(200, {'Content-Type':
'text/html'});
res.write(data);
res.end();
});
}).listen(8080);
See below output-
Custom module can also be created and used same
as above.
To create custom module use exports keyword, refer below snippet-
exports.dateTime = function () {
return
Date();
};
Save above code in date-time.js file and run it
will create module with name date-time
Now we can use as follows-
var http = require('http');
var dt = require('date-time’);
http.createServer(function
(req, res) {
res.writeHead(200, {'Content-Type':
'text/html'});
res.write("Current date: " + dt.dateTime());
res.end();
}).listen(8080);