How to read and write files in Node JS ?
Last Updated :
06 Feb, 2024
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 metadata. Let's explore how to read and write files in NodeJS.
Reading Files:
To read from a file in NodeJS, you can use the fs.readFile()
method. This method asynchronously reads the entire contents of a file and passes the data to a callback function.
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (error, data) => {
if (error) {
console.error('An error occurred while reading the file:', error);
return;
}
console.log('File content:', data);
});
Writing Files:
To write to a file in NodeJS, you can use the fs.writeFile()
method. This method asynchronously writes data to a file, replacing the file if it already exists or creating a new file if it doesn't exist.
const fs = require('fs');
const content = 'This is the content to be written to the file.';
fs.writeFile('example.txt', content, 'utf8', (error) => {
if (error) {
console.error('An error occurred while writing to the file:', error);
return;
}
console.log('File has been written successfully.');
});
Synchronous File Operations:
NodeJS also provides synchronous versions of file operations, such as fs.readFileSync()
and fs.writeFileSync()
, which block the execution thread until the operation completes. While synchronous operations may be suitable for certain use cases, they can potentially block the event loop and impact the overall performance of the application, especially in I/O-bound scenarios.
Handling File Paths:
When working with file paths in NodeJS, it's essential to handle path resolution and normalization correctly, especially when dealing with relative paths. NodeJS provides the path
module to help manipulate file paths cross-platform.
const path = require('path');
const absolutePath = path.resolve(__dirname, 'example.txt');
Conclusion:
NodeJS offers powerful modules for reading and writing files asynchronously, enabling developers to interact with the file system seamlessly. By using methods provided by the fs
module, handling file operations asynchronously, and properly managing file paths, developers can build robust and efficient file processing applications in NodeJS.
Similar Reads
How to read and write JSON file using Node ? Node JS is a free and versatile runtime environment that allows the execution of JavaScript code outside of web browsers. It finds extensive usage in creating APIs and microservices, catering to the needs of both small startups and large enterprises.JSON(JavaScript Object Notation) is a simple and t
3 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 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 a File Line By Line Using Node.js? To read a file line by line in Node.js, there are several approaches that efficiently handle large files and minimize memory usage. In this article, we'll explore two popular approaches: using the Readline module (which is built into Node.js) and using the Line-reader module, a third-party package.
3 min read
How to Access the File System in Node.js ? 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 ES6Basic knowledge of NodeJS NodeJS is one of the most popular server-side programming frameworks running on the JavaScript V8 engine, which uses
3 min read
How to Download a File Using Node.js? Downloading files from the internet is a common task in many Node.js applications, whether it's fetching images, videos, documents, or any other type of file. In this article, we'll explore various methods for downloading files using Node.js, ranging from built-in modules to external libraries.Using
3 min read
How to Add Data in JSON File using Node.js ? JSON stands for Javascript Object Notation. It is one of the easiest ways to exchange information between applications and is generally used by websites/APIs to communicate. For getting started with Node.js, refer this article.Prerequisites:NPM NodeApproachTo add data in JSON file using the node js
4 min read
How to Update Data in JSON File using Node? To update data in JSON file using Node.js, we can use the require module to directly import the JSON file. Updating data in a JSON file involves reading the file and then making the necessary changes to the JSON object and writing the updated data back to the file. Table of ContentUsing require() Me
4 min read
How to truncate a file using Node.js ? In this article, we are going to explore How to truncate the complete file using Node. There are two methods to truncate the file of all its data. We can either use the fs.truncate() method or the fs.writeFile() method to replace all the file content. Method 1: The fs.truncate() method in Node.js ca
3 min read
How to handle file upload in Node.js ? File upload can easily be done by using Formidable. Formidable is a module that we can install on our project directory by typing the commandnpm install formidableApproach: We have to set up a server using the HTTPS module, make a form that is used to upload files, save the uploaded file into a temp
3 min read