lec 3
lec 3
js Modules
Modules in Node are the reusable blocks of code that encapsulate various functionalities in a
Node application. These modules can include functions, objects, and variables that are
exported from the code files.
• Consider modules to be the same as JavaScript libraries.
• A set of functions you want to include in your application.
Type of Node.js Modules
1- Core Modules
Node.js has a set of built-in modules which you can use without any further installation.
To include a module, use the require() function with the name of the module:
var http = require('http');
Now your application has access to the HTTP module, and is able to create a server:
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello World!');
}).listen(8080);
2- Local Modules (Your Own Modules)
Unlike built-in and external modules, local modules are created locally in your
Node.js application.
The following example creates a module that returns a date and time object:
Example
exports.myDateTime = function () {
return Date();
};
exports keyword to make properties and methods available outside the module
file.
Save the code above in a file called "myfirstmodule.js"
Now you can include and use the module in any of your Node.js files.
Use the module "myfirstmodule" in a Node.js file:
var http = require('http');
var dt = require('./myfirstmodule');
Example
Create two html files and save them in the same folder as your node.js files.
summer.html
<!DOCTYPE html>
<html>
<body>
<h1>Summer</h1>
<p>I love the sun!</p>
winter.html
<!DOCTYPE html>
<html>
<body>
<h1>Winter</h1>
<p>I love the snow!</p>
</body>
</html>
Create a Node.js file that opens the requested file and returns the content to the
client. If anything goes wrong, throw a 404 error:
demo_fileserver.js:
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);
Initiate demo_fileserver.js:
you should see two different results when opening these two addresses:
http://localhost:8080/summer.html
Will produce this result:
Summer
I love the sun!
http://localhost:8080/winter.html
Will produce this result:
Winter
I love the snow!
Node.js File System Module
The Node.js file system module allows you to work with the file system on your
computer.
var fs = require('fs');
Synchronous vs Asynchronous
Every method in the fs module has synchronous as well as asynchronous version
The asynchronous methods are non-blocking in nature as compared to the
synchronous methods.
fs.writeFileSync(file, data[, options])
fs.writeFile(file, data[, options], callback)
Writing a file
The following program shows how to write data in a file with synchronous as well
as asynchronous methods.
const fs = require('fs');
var text = `Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!`;
console.log("Writing synchronously");
fs.writeFileSync("input.txt", text);
console.log("Writing asynchronously");
fs.writeFile('input.txt', text, function (err) {
if (err)
console.log(err);
else
console.log('Write operation complete.');
});
Output ??
Reading a file
The ReadFile() method in fs module reads a file asynchronously. On the other hand, the
ReadFileSync() method is its synchronous version.
Example
const fs = require('fs');
console.log("Reading synchronously");
data = fs.readFileSync("input.txt");
console.log(data.toString());
console.log("Reading asynchronously");
fs.readFile('input.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});
console.log('Read operation complete.');
Output
Reading synchronously
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
Reading asynchronously
Read operation complete.
Asynchronous read: Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
Open a file
The open() method has the following signature −
fs.open(path, flags[, mode], callback)
• path − This is the string having file name including path.
• flags − Flags indicate the behavior of the file to be opened.
• mode − It sets the file mode, but only if the file was created. It defaults to 0666, readable and writeable.
• callback − This is the callback function which gets two arguments (err, fd).
Let us open a file “input.txt” for writing data into it.
// Open a file for writing
const fd = fs.open('input.txt', 'w', (err, fd) => {
if (err) {
console.log(err);
return;
}
To open() method returns a reference to the file, called as File Descriptor. A file descriptor is a
unique integer, and used as an argument for the methods performing write and read
operations.
Example
const fs = require('fs');
// Open a file for writing
const fd = fs.open('input.txt', 'w', (err, fd) => {
if (err) {
console.log(err);
return;
}
// Write some data to the file
var data = `Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!! `;