Node.js / Node.js Modules
Using Built-in Modules like FS and HTTP
In this tutorial, we will delve into some of the built-in modules in Node.js, specifically the 'fs' and 'http' modules. We will learn how these modules can be used to handle files…
Section overview
5 resourcesExplores built-in, third-party, and custom modules in Node.js.
Using Built-in Modules like FS and HTTP
1. Introduction
This tutorial aims to familiarize you with two of Node.js's built-in modules: fs and http. These modules are used for handling files and establishing servers, respectively.
By the end of this tutorial, you'll be able to read, write, and delete files using the fs module. You'll also learn how to create a basic HTTP server using the http module.
Prerequisites: Basic knowledge of JavaScript and Node.js is recommended.
2. Step-by-Step Guide
The Node.js filesystem (fs) module allows you to interact with the file system on your computer. It can be used to perform CRUD (Create, Read, Update, Delete) operations on files and directories.
The HTTP (http) module stands for HyperText Transfer Protocol. It's a protocol used to transfer data over the web. In Node.js, the http module allows you to transfer data over the internet.
Let's explore these modules further.
The FS Module
The fs module can be included in your application as follows:
const fs = require('fs');
Reading Files
To read a file, use the fs.readFile() method:
fs.readFile('test.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
In this example, test.txt is the name of the file we want to read. utf8 is the character encoding, and the function (err, data) is a callback function that returns the file content (data).
Writing Files
The fs.writeFile() method is used for writing new files:
fs.writeFile('test.txt', 'Hello, World!', (err) => {
if (err) throw err;
console.log('File has been saved!');
});
Here, Hello, World! is the text we want to write to test.txt.
The HTTP Module
Include the http module in your application as follows:
const http = require('http');
Creating a Server
To create a server, use the http.createServer() method:
const server = http.createServer((req, res) => {
res.end('Hello, World!');
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});
In this example, the server listens on port 3000. When a client connects, the server responds with "Hello, World!".
3. Code Examples
Example 1: Reading a File
const fs = require('fs');
fs.readFile('test.txt', 'utf8', (err, data) => {
if (err) {
console.log(err);
} else {
console.log(data);
}
});
In this example, the readFile method is used to read a file named test.txt. The utf8 parameter specifies the encoding. The function (err, data) is a callback that is invoked after the file has been read. It logs the file's content to the console.
Example 2: Creating a Server
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello, World!');
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});
In this example, the http module's createServer method is used to create an HTTP server. The server listens on port 3000 and responds with "Hello, World!" to any requests.
4. Summary
In this tutorial, we've covered how to use the fs and http modules in Node.js. You've learned how to read and write files with fs, and how to create a server with http.
To continue your learning, explore other built-in Node.js modules and practice using them in your projects. For more information, visit the Node.js Docs.
5. Practice Exercises
Exercise 1: Write a JavaScript program that uses the fs module to create a new file named myFile.txt and write "This is my file" in it.
Exercise 2: Write a JavaScript program that uses the http module to create a server. The server should respond with "Welcome to my server!" when accessed.
Exercise 3: Write a JavaScript program that uses both the fs and http modules. When the server is accessed, it should read a file named myFile.txt and display its content.
Solution 1:
const fs = require('fs');
fs.writeFile('myFile.txt', 'This is my file', (err) => {
if (err) throw err;
console.log('File has been saved!');
});
Solution 2:
const http = require('http');
const server = http.createServer((req, res) => {
res.end('Welcome to my server!');
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});
Solution 3:
const fs = require('fs');
const http = require('http');
const server = http.createServer((req, res) => {
fs.readFile('myFile.txt', 'utf8', (err, data) => {
if (err) throw err;
res.end(data);
});
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article