How to Access the File System in Node.js ?
Last Updated :
19 Oct, 2021
In this article, we looked at how to access the file system in NodeJS and how to perform some useful operations on files.
Prerequisite:
- Basic knowledge of ES6
- Basic knowledge of NodeJS
NodeJS is one of the most popular server-side programming frameworks running on the JavaScript V8 engine, which uses a single-threaded non-blocking I/O model. We can access the file system in NodeJS using some inbuilt modules.
File System: A file is a collection of related information stored in secondary storage Or a file is a collection of similar types of entities that work with the file and manage it also called a File System.Â
If you want to know more about the file system refer to this article.
File System Module (fs module): One of the popular inbuilt modules for working with the file system in NodeJS is the file system module which is also called the "fs" module in short. fs module is very powerful for doing any task in NodeJS related to File systems.
Access the File System in Node JS means performing some basic operations on files. This is also known as CRUD operations.
CRUD Operations:
- C => Create the files
- R => Read the files
- U => Update the files
- D => Delete the file
Basic operations on files using the "fs" module:
Step 1: Create a file with ".js" extension.
Step 2: Add the "fs" module to the codebase.
Syntax:
const fs = require('fs');
After required the fs module, you can perform the following operations on files:
Operation 1: Create a File
Syntax:
const fs = require('fs');
fs.writeFileSync('./{file_name}', 'Content_For_Writing');
The fs.writeFileSync method is used to write something to the file, but if the file does not exist, it creates new files along with writing the contents.
Operation 2: Read the File
Syntax:
const fs = require('fs');
const file_content = fs.readFileSync('./{file_name}',
'{content_formate}').toString();
// For show the data on console
console.log(file_content);
The fs.readFileSync method is used to read data from a file, the first argument to readFileSync is the path to the file, and the second argument takes the options {format, flag, etc} and returns the buffer object of the stream. So we can use the buffer String assigned to a variable named file_content using toString() method and after assigning data to file_content the data is shown on the console using console.log() method.
Operation 3: Update the File
Syntax:
const fs = require('fs');
fs.appendFileSync('./{file_name}', " {Updated_Data}");
const file_content = fs.readFileSync(
'./{file_name}', '{file_formate}').toString();
console.log(file_content);
The fs.appendFileSync method is used for updating the data of a file.
Operation 4: Delete a File
const fs = require('fs');
fs.unlinkSync('./{file_name}');
The fs.unlinkSync() method is used to delete the file with passing the file name.
Below is the code implementation for the above operations:
Example:
The filename is index.js
JavaScript
const fs = require('fs');
/* The fs.writeFileSync method is used
to write something to the file, but if
the file does not exist, it creates new
files along with writing the contents */
fs.writeFileSync('./testfile', 'This is a file');
var file_content = fs.readFileSync(
'./testfile', 'utf8').toString();
console.log(file_content);
/* The fs.appendFileSync method is used
for updating the data of a file */
fs.appendFileSync('./testfile', " Updated Data");
file_content = fs.readFileSync(
'./testfile', 'utf8').toString();
console.log(file_content);
/* The fs.unlinkSync method are used to delete
the file. With passing the file name */
fs.unlinkSync('./testfile');
Try Out the code and run it using node.js by using the following command:
node index.js
Finally, we saw how to access the file system and also tried many operations on it.
Similar Reads
How to Copy a File in Node.js?
Node.js, with its robust file system (fs) module, offers several methods to copy files. Whether you're building a command-line tool, a web server, or a desktop application, understanding how to copy files is essential. This article will explore various ways to copy a file in Node.js, catering to bot
2 min read
How to read and write files in Node JS ?
NodeJS provides built-in modules for reading and writing files, allowing developers to interact with the file system asynchronously. These modules, namely fs (File System), offer various methods for performing file operations such as reading from files, writing to files, and manipulating file metada
2 min read
How to Access Cache Data in Node.js ?
Caching is an essential technique in software development that helps improve application performance and scalability by temporarily storing frequently accessed data. In Node.js, caching can significantly reduce database load, minimize API response times, and optimize resource utilization. This artic
5 min read
How to Create a Dockerfile in Node.js ?
A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image. It is something like a shellscript that gathers multiple commands into a single document to fulfill a single task. Prerequisite: Before you can Dockerize any application, you ne
4 min read
How to work with Node.js and JSON file ?
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. With node.js as backend, the developer can maintain a single codebase for an entire application in javaScript.JSON on the other hand, stands for JavaScript Object Notation. It is a lightweight format for storing and exchanging d
4 min read
How to Setup View Engine in Node.js ?
View engines are useful for rendering web pages. There are many view engines available in the market like Mustache, Handlebars, EJS, etc but the most popular among them is EJS which simply stands for Embedded JavaScript. It is a simple templating language/engine that lets its user generate HTML with
2 min read
What is File System Module in Node.js ?
Node.js is a powerful platform for building server-side applications, and one of its key features is its ability to interact with the file system. The File System (fs) module in Node.js provides an extensive API to work with files and directories, allowing developers to perform operations such as re
3 min read
How to check the given path is file or directory in node.js ?
Sometimes there is a need to check whether the given path is a file or directory so that different operations can be performed based on the result. For instance, to log the information of the directory and file separately. In Node.js, file handling is handled by the fs module. You can read more abo
4 min read
Node.js File System
The fs (File System) module in Node.js provides an API for interacting with the file system. It allows you to perform operations such as reading, writing, updating, and deleting files and directories, which are essential for server-side applications and scripts.Table of ContentNode.js file systemKey
9 min read
How To Serve Static Files in ExpressJS?
ExpressJS is a popular web framework for NodeJS that allows developers to build robust web applications. One of its core functionalities is serving static files such as images, CSS, JavaScript, and HTML files.Syntaxapp.use(express.static(path.join(__dirname, 'public')));Serves Static Files: This lin
2 min read