π₯What is Modules?
A module encapsulates related code into a single unit of code. When creating a module, this can be interpreted as moving all related functions into a file.
π₯How to create Module
πCreate a module that returns the current date and time:
πexports.myDateTime = function () {
return Date();
};
πSave the code above in a file called "firstmodule.js"
πNow we can include and use the module in any of our Node.js files.
π var http = require('http');
var dt = require('./myfirstmodule');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("The date and time is currently: " + dt.myDateTime());
res.end();
}).listen(8080);
πSave the code above in a file called "demo_module.js", and initiate the file
πInitiate demo_module.js in Terminal
C:\Users\Your Name> node demo_module.js
π If we want result,We will use this path http://localhost:8080
π₯ Node.js HTTP Module
πThis allows Node.js to transfer
data over the Hyper Text Transfer Protocol (HTTP).
π var http = require('http');
//create a server object:
http.createServer(function (req, res) {
res.write('Hello World!'); //write a response to the client
res.end(); //end the response
}).listen(8080); //the server object listens on port 8080
πSave the code above in a file called "demo_http.js"
πthen use below code in terminal
C:\Users\Your Name>node demo_http.js
π Then use port to open browser
out put:
Hello World!
π₯Node.js URL Module
πCreate two html files and save them in the same folder as your node.js files.
πvar http = require('http');
var url = require('url');
var fs = require('fs');
http.createServer(function
(req, res) {
var q = url.parse(req.url, true);
var
filename = "." + q.pathname;
fs.readFile(filename,
function(err, data) {
if (err) {
res.writeHead(404, {'Content-Type': 'text/html'});
return res.end("404 Not Found");
}
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
π node demo_fileserver.js
πhttp://localhost:8080/(htmlfilename)
No comments:
Post a Comment