0% found this document useful (0 votes)
6 views

lec 3

The document provides an overview of Node.js modules, including core, local, and third-party modules, and explains how to create and use them in applications. It details the built-in HTTP and URL modules for handling web requests and responses, as well as the file system module for file operations. Additionally, it covers examples of writing, reading, appending, and deleting files, along with creating directories in Node.js.

Uploaded by

deadinsideayayy
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

lec 3

The document provides an overview of Node.js modules, including core, local, and third-party modules, and explains how to create and use them in applications. It details the built-in HTTP and URL modules for handling web requests and responses, as well as the file system module for file operations. Additionally, it covers examples of writing, reading, appending, and deleting files, along with creating directories in Node.js.

Uploaded by

deadinsideayayy
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Node.

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');

http.createServer(function (req, res) {


res.writeHead(200, {'Content-Type': 'text/html'});
res.write("The date and time are currently: " + dt.myDateTime());
res.end();
}).listen(8080);
Save the code above in a file called "demo_module.js", and initiate the file:
C:\Users\Your Name>node demo_module.js
• you will see the same result as the example: http://localhost:8080
3- Third-party modules
Third-party modules are modules that are available online using the Node Package
Manager(NPM). These modules can be installed in the project folder or globally.
Example: Installing and Using Express
Npm install express
Create a Simple Express Server:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
the app responds with “Hello World!” for requests to the root URL (/) or route. For every
other path, it will respond with a 404 Not Found.
Run the Server: Use this command to run the node application.
node server.js When you navigate to localhost:3000 you see the result
The Built-in HTTP Module
Node.js has a built-in module called HTTP, which allows Node.js to transfer data
over the Hyper Text Transfer Protocol (HTTP).
Use createServer() method to create an HTTP server:
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
Add an HTTP Header
• If the response from the HTTP server is supposed to be displayed as HTML, you
should include an HTTP header with the correct content type:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Hello World!');
res.end();
}).listen(8080);
res.writeHead() method is the status code, 200 means that all is OK, the second
argument is an object containing the response headers.
Read the Query String
The function passed into the http.createServer() has a req argument that
represents the request from the client, as an object
This object has a property called "url" which holds the part of the url that comes
after the domain name:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(req.url);
res.end();
}).listen(8080);
save the code above in a file and initiate the file:
you should see two different results when opening these two addresses:
http://localhost:8080/summer
• Will produce this result:
/summer
http://localhost:8080/winter
Will produce this result:
??
The Built-in URL Module
The URL module splits up a web address into readable parts.
Parse an address with the url.parse() method, and it will return a URL object with
each part of the address as properties:
Example
Split a web address into readable parts:
var url = require('url');
var adr = 'http://localhost:8080/default.htm?year=2017&month=february';
var q = url.parse(adr, true);
console.log(q.host); //returns 'localhost:8080'
console.log(q.pathname); //returns '/default.htm'
console.log(q.search); //returns '?year=2017&month=february'

var qdata = q.query; //returns an object: { year: 2017, month: 'february' }


console.log(qdata.month); //returns 'February’
pass true as the second argument to also parse the query.

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!!!!! `;

fs.write(fd, data, (err) => {


if (err) {
console.log(err);
return;
}
// Close the file
fs.close(fd, (err) => {
if (err) {
console.log(err);
return;
}
console.log('The file was written successfully!');
});
});
});

See file openfilew.js


To read back the file, it must be opened in read mode. The read() method in fs
module uses the file descriptor and retrieves the data in it in a buffer object.
read(fd, buffer[, options], callback)
Parameters
• fd − file descriptor
• buffer − The buffer that the data will be written to.
• options − offset, length and position
• callback − function to be invoked.
To read back the data in input.txt, use the read() method as follows −
See file openfiler.js
Example
var fs = require('fs');
fs.open('input.txt', 'r', function (err, fd) {
if (err) {
return console.error(err);
}
var buffr = Buffer.alloc(1024);
fs.read(fd, buffr, function (err) {

if (err) throw err;


else
console.log(buffr.toString());
});
// Close the opened file.
fs.close(fd, function (err) {
if (err) throw err;
});
});
appendFile
fs.appendFile() method appends the specified content at the end of the specified
file:
Example
Append "This is my text." to the end of the file "mynewfile1.txt":
var fs = require('fs');

fs.appendFile('mynewfile1.txt', ' This is my text.', function (err) {


if (err) throw err;
console.log('Updated!');
});
Delete a File
Following is the syntax of the method to delete a file −
fs.unlink(path, callback)
Example
var fs = require("fs");

console.log("Going to delete an existing file");


fs.unlink('input.txt', function (err) {
if (err) {
return console.error(err);
}
console.log("File deleted successfully!");
});
Create a Directory
Following is the syntax of the method to create a directory −
fs.mkdir(path[, mode], callback)
Example
var fs = require("fs");
const path = require('path');
console.log("Going to create directory /test");
fs.mkdir(path.join(__dirname, 'test'),
(err) => {
if (err) {
return console.error(err);
}
console.log('Directory created successfully!');
});
See file makedir.js

You might also like