Read Data From File in Node Js
Trending blog posts
How to read files with Node.js?
6K
- by Shubham Chadokar
- 03rd Jul, 2020
- Last updated on 15th Mar, 2021
- v mins read
In this tutorial, we volition explore different ways we can read files in Node . js.
In software development, reading files is a regular office of the chore. However, this unproblematic process very often becomes complicated and irksome. Fortunately, that'south not the case in Node . js. Node.js provides a bornfile system(fs) module, to acquit out file operations.
Before we start, let usa make sure we have the basic prerequisites. You volition need to ensure yous have:
- Node.js
- Lawmaking Editor (Ex. VS Lawmaking, Cantlet)
For this tutorial, my environment setup includes:
- Node.js - v12.sixteen.ane
- Code Editor - VS Code
fs module
fs module is a born module in the Node.js. You lot do notnecessarily demand to install it.
The fs module supports both Synchronous and Asynchronous function calls.
Getting s tarted
I am assuming y'all have installed the NodeJS.
- Create a new directory node-fs.
- Create 2 files inside the node-fs, data.txt and alphabetize.js.
- Paste the dummy data in the data.txt.
Lorem ipsum dolor sit amet, consecteturadipiscingelit, sed practise eiusmodtemporincididuntutlabore et dolore magna aliqua.
Open up this directory in the code editor.
From the index.js, we will read the test.txt.
Read file Synchronously using readFileSync
The readFileSync is a synchronous method to read a file.
Syntax
fs.readFileSync(path[, options])
- pathfilepath
- options
- encoding string or buffer Default goose egg
- flag string Default r
Open index.js in the Lawmaking Editor.
Paste the below code.
// import the fs module const fs = crave("fs"); // read file synchronously constreadData =fs.readFileSync("./data.txt"); panel.log(readData);
Open the terminal or cmd in the node-fs directory and run the below command.
$ node alphabetize.js <Buffer4c 6f 72 65 6d 20 69 seventy 73 75 6d xx 64 6f 6c 6f 72 20 73 69 74 twenty 61 6d 65 74 2c 20 63 6f 6e 73 65 63 74 65 74 75 72 20 61 64 69 lxx 69 73 63 69 6e 67 ... 73 more bytes>
It has returned the content in the buffer format. The readFileSync by default returns the content in the Buffer format.
To get the content in normal string format, we need to pass the utf8 encoding as a parameter.
Alter the code.
// import the fs module const fs =require("fs"); // read file synchronously constreadData =fs.readFileSync("./data.txt","utf8"); console.log(readData);
run it.
$ node index.js
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Read file Asynchronously using readFile
Asynchronous methods are great when yous don't want to look for a procedure to complete.
fs module provides an asynchronous method to read a file. It returns a callback.
Syntax
fs.readFileSync(path[, options], callback)
- pathfilepath
- options
- encoding string or buffer Default null
- flag string Defaultr
- callback role
- err Error
- data string | Buffer
Syntax is like tothe synchronous method except information technology returns a callback office.
// import the fs module const fs =require("fs"); // read file asynchronously fs.readFile("./data.txt","utf8", (err,information)=> { if (!err) { console.log(data); }else {console.fault("Something went incorrect while reading the file."); } });
Run the code.
$ node index.js
Lorem ipsum dolor sit down amet, consectetur adipiscing elit, sed exercise eiusmod tempor incididunt ut labore et dolore magna aliqua.
Read file using Stream
Reading file using fs.readFileis an ideal way if the file size is less. If the size is huge, the read will consume the complete Memory and you may detect your system hanging.
In such scenarios, Stream is the best option. This breaks the file into pocket-size chunks of data and sends a piece at a time. In this way, the arrangement tin can go along with other tasks without allocating the complete retention to it.
Permit usa lawmaking and empathize.
Node.js provides a createReadStreammethod to stream the file. createReadStreamreturns a fs.ReadStreamobject. The readStream events similar information, cease, or error.To read the file, we have to listen to these events.
- The dataupshot volition render the content of the file in chunks.
- The terminateeffect volition notify that, at that place is no data left in the file to read.
- The errorevent returns an error.
// import the fs module constfs =crave("fs"); // read file using stream const streamRead =async () => { return new Promise((resolve,reject)=> { attempt { // create a read stream const streamRead =fs.createReadStream("./data.txt", { encoding:"utf8", }); // heed to data event streamRead.on("information", (data)=> { console.log(data); }); // listen to finish event streamRead.on("end", ()=>{ resolve("File read consummate"); }); // listen to mistake outcome streamRead.on("error", (error)=> { throw Error( "Something went wrong while streaming the file.", error.message ); }); }catch (error) { reject(mistake); } }); }; streamRead().and then((res,err) => { if(!err)console.log(res); else console.error(err); });
Run the code.
$ node index.js
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. File read complete
Experiment t ime !
For the purpose of the experiment, I created a file of 2 0MBto bank check the performance of readFileSync, readFileand createReadStream .
The average retentivity consumption of VS Code is 600-700MB in my auto.
This is a screenshot before running any of the commands.
readFileSync
Check the screenshot. This operation took 373MB and it went on to upto ~450MB .
readFile (Asynchronous)
Check the screenshot. This functioning took 506MB and it went on to upto ~600MB.
createReadStream
Check the screenshot. This operation took 287MB and it reached upto ~300MB.
Conclusion
Node.js provides multiple methods to read a file. Information technology completely depends on the file size and the requirement, which method to choose. From our performance tests, streaming turns out to exist the most efficient method to use.
The performance may vary from motorcar to auto and file size. One must note that what we take demonstrated is merely for the sake of a demo, so this must non be taken to be the terminal words. In that location are other npm packages available for file system, for example,fs-extra.
Promise this tutorial has helped. Taking a formal training course in Node.js would exist a nifty way to fast-track your career.
Happy coding!
Tired of fixing bugs? Find piece of cake solutions to your programming queries with our live, interactive workshops. Explore now.
SPECIAL OFFER Upto 50% off on all courses
Enrol Now
Trending blog posts
Suggested Blogs
Source: https://www.knowledgehut.com/blog/web-development/read-files-nodejs
0 Response to "Read Data From File in Node Js"
Post a Comment