JIYIK CN >

Current Location:Home > Learning > PROGRAM > Node.js >

Reading Files in Node.js

Author:JIYIK Last Updated:2025/04/17 Views:

In this short article, we will learn how to read files in Node.js.

Reading Files in Node.js

fsThe module provides many useful functions to access and interact with the file system. fsOne special feature of the module is that all methods are asynchronous by default, but can also be made to work synchronously by adding sync.

We will use fs.readFile()to read the file in Node.js. You need to pass the file path, encoding, and a callback function to call with the file data or error.

fs.readFile()method is a built-in method for reading files. It reads the entire file into a buffer. require()method is used to load modules, such as const fs = require('fs').

grammar:

fs.readFile( filename, encoding, callbackFn )

This method accepts three parameters.

callbackFn Parameters illustrate
err If any error occurs while reading the file.
data The contents of the file being read.

It returns the content, data stored in the file or error encountered while reading the file. Let us understand it with an example.

Code:

const fs = require('fs');
fs.readFile('/helloworld.txt', 'utf8', (err, data) => {
  if (err) {
    console.error(err);
    return;
  }
  console.log(data);
});

The output is as follows:

Hello jiyik.com readers!

Another option is to use the synchronous version fs.readFileSync().

Code:

const fs = require('fs');
try {
  const fileContent = fs.readFileSync('/helloworld.txt', 'utf8');
  console.log(fileContent);
} catch (err) {
  console.error(err);
}

The output is as follows:

Hello jiyik.com readers!

We can also use the method provided by the fs/promises module fsPromises.readFile().

Code:

const fsPromises = require('fs/promises');

async function FileReadFn() {
  try {
    const fileContent = await fsPromises.readFile('/helloworld.txt', { encoding: 'utf8' });
    console.log(fileContent);
  } catch (err) {
    console.log(err);
  }
}
FileReadFn();

The output is as follows:

Hello jiyik.com readers!

fs.readFile()fsPromises.readFile()All fs.readFileSync()three methods read the entire contents of the file into memory before returning the data. This means that large files will greatly affect memory usage and program execution speed .

Rather than waiting for the file to finish reading, we start streaming to the HTTP client as soon as the data is ready to be sent. Streams essentially offer two major advantages over using other methods of data processing.

  1. Memory efficiency – You don’t have to load large amounts of data into memory before processing.
  2. Time efficiency - It takes much less time to start processing data because you can start processing immediately instead of waiting until the entire payload is available.

On the file stream, call pipe()the method, which takes the source and directs it to the destination. The destination stream is pipe()the return value of the method, which is a very convenient thing that allows us to pipe()chain together multiple calls to .

Code:

const fs = require('fs');
const http = require('http');

const nodeServer = http.createServer((req, res) => {
  const fileStream = fs.createReadStream(`${__dirname}/helloworld.txt`);
  fileStream.pipe(res);
});
nodeServer.listen(3000);

The output is as follows:

Hello jiyik.com readers!

Previous: None

Next:HTTP POST request in Node.js

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Throwing Errors in Node.js

Publish Date:2025/04/17 Views:164 Category:Node.js

This article will explain how to throw errors in Node.js. Throwing Errors in Node.js Errors are statements that do not allow the system to function properly. Errors in Node.Js are handled through exceptions, which are created with the help

Solve the Cannot Find Module error in Node.js

Publish Date:2025/04/17 Views:70 Category:Node.js

In this article, we will learn how to fix the Cannot find module error in Node.js. package.json File Before diving into the solution, we will first try to understand the package.json file and why we need it. The package.json file is the roo

Multithreading in Node.js

Publish Date:2025/04/17 Views:112 Category:Node.js

In Node.js, the term multithreading does not apply because Node.js is designed to run in a single-threaded event loop. However, Node.js is built on top of the JavaScript language, which is single-threaded by default. However, Node.js provid

Using jQuery in Node.js

Publish Date:2025/04/17 Views:51 Category:Node.js

jQuery is a popular JavaScript library that is widely used to build web applications. It provides a rich set of APIs for interacting with the DOM, making HTTP requests, handling events, etc. Node.js is a JavaScript runtime that allows devel

Node.js sends files to the client

Publish Date:2025/04/17 Views:70 Category:Node.js

In this article, we will learn how to send files to the client in Node.js using Express. Sending files using Express in Node.js Express.js or Express is a backend web utility framework for Node.js. Express is a Node.js web application frame

HTTP POST request in Node.js

Publish Date:2025/04/17 Views:131 Category:Node.js

In this article, we will learn how to use Node.js to make a post request using a third-party package. HTTP Post Request in Node.js The HTTP POST method creates or adds resources on the server. The key difference between POST and PUT request

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial