English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
We will learn to read files in Node.js using the Node FS (built-in file system module). A Node.js example program using the readFile() function is provided.
Read a file in Node.js
No.1StepThe following is a step-by-step guide to reading file content in Node.js:
: Include the File System built-in module in the Node.js programvar fs = require('fs'); |
);2Step
: Use the readFile function to read the filefileName>’,<callbackFunction>) |
: Provide a callback function as a parameter of the readFile function. After the file is read (with or without an error), err (if there is an error reading the file) and the callback function data (if the file is read successfully) will be used.
No.3Step: Create a sample file, for example sample.html, which contains some content. Place the sample file in the location provided below for the node.js example program.
// Import the File System module var fs = require('fs'); // Read the file sample.html fs.readFile('sample.html', // Callback function called when the file reading is completed function(err, data) { if (err) throw err; // The data is a buffer containing the content of the file console.log(data.toString('utf-8'));8')); });
Run the program using the node command in the terminal or command prompt:
Terminal Output
$ node readFileExample.js <html> <body> <h1>Header</h1> <p>I have learned to read a file in Node.js.</p>/p> </body> </html>
In this Node.js tutorial – Node FS, we learned how to read a file in Node.js using the built-in File System module. A Node.js example program using the readFile() function is provided.