How to Read From a File Nodejs

Trending web log posts

How to read files with Node.js?

6K

  • by Shubham Chadokar
  • 03rd Jul, 2020
  • Final updated on 15th Mar, 2021
  • 5 mins read

How to read files with Node.js?

In this tutorial, we will explore different means we can read files in Node . js.

In software evolution, reading files is a regular office of the job. Withal, this simple process very frequently becomes complicated and wearisome. Fortunately, that'south not the case in Node . js. Node.js provides a congenital-infile system(fs) module, to behave out file operations.

Before nosotros start, let united states of america make sure we have the bones prerequisites. You lot will need to ensure yous accept:

  • Node.js
  • Code Editor (Ex. VS Code, Cantlet)

For this tutorial, my surroundings setup includes:

  • Node.js - v12.16.i
  • Code Editor - VS Code

fs module

fs module is a built-in module in the Node.js. You do notnecessarily demand to install it.

The fs module supports both Synchronous and Asynchronous office calls.

Getting s tarted

I am assuming you take installed the NodeJS.

  • Create a new directory node-fs.
  • Create 2 files inside the node-fs, data.txt and alphabetize.js.
  • Paste the dummy information in the data.txt.

Lorem ipsum dolor sit amet, consecteturadipiscingelit, sed exercise eiusmodtemporincididuntutlabore et dolore magna aliqua.

Open this directory in the lawmaking 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 nothing
    • flag cord Default r

Open up index.js in the Code Editor.

Paste the beneath code.

                // import the fs module                const fs = require("fs");                // read file synchronously                                constreadData =fs.readFileSync("./data.txt");                panel.log(readData);

Open the concluding or cmd in the node-fs directory and run the below command.

$ node index.js <Buffer4c 6f 72 65 6d 20 69 70 73 75 6d twenty 64 6f 6c 6f 72 20 73 69 74 xx 61 6d 65 74 2c 20 63 6f 6e 73 65 63 74 65 74 75 72 20 61 64 69 seventy 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 go the content in normal string format, we need to pass the utf8 encoding as a parameter.

Change the code.

                // import the fs module                                const fs =require("fs");                // read file synchronously                                constreadData =fs.readFileSync("./information.txt","utf8");                panel.log(readData);

run information technology.

$ 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 y'all don't want to await for a process to consummate.
fs module provides an asynchronous method to read a file. Information technology returns a callback.
Syntax

fs.readFileSync(path[, options], callback)
  • pathfilepath
  • options
    • encoding string or buffer Default null
    • flag string Defaultr
  • callback function
    • err Error
    • information cord | Buffer

Syntax is similar tothe synchronous method except it returns a callback part.

                // import the fs module                                const fs =require("fs");                // read file asynchronously                                fs.readFile("./data.txt","utf8", (err,information)=> {  if (!err) { panel.log(data);     }else {panel.mistake("Something went wrong while reading the file.");     } });

Run the lawmaking.

$ node index.js
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed practice eiusmod tempor incididunt ut labore et dolore magna aliqua.

Read file using Stream

Reading file using fs.readFileis an platonic way if the file size is less. If the size is huge, the read will consume the complete Memory and you may discover 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 organization can continue with other tasks without allocating the complete memory to it.

Let u.s.a. code and understand.

Node.js provides a createReadStreammethod to stream the file. createReadStreamreturns a fs.ReadStreamobject. The readStream events like data, cease, or error.To read the file, we have to listen to these events.

  • The dataeffect will render the content of the file in chunks.
  • The endissue will notify that, there is no data left in the file to read.
  • The erroreffect returns an error.
                // import the fs module                                constfs =require("fs");                // read file using stream                                const                streamRead =async () => {                return                new                Promise((resolve,turn down)=> {                attempt {                // create a read stream                                const                streamRead =fs.createReadStream("./information.txt", {                encoding:"utf8",        });                // heed to data event                                streamRead.on("data", (data)=> {                panel.log(data);        });                // mind to end event                                streamRead.on("end", ()=>{                resolve("File read complete");        });                // listen to error event                                streamRead.on("mistake", (error)=> {                throw                Error(                "Something went incorrect while streaming the file.",                error.bulletin                                );        });      }catch (error) {                reject(error);      }    });  };                streamRead().and then((res,err) => {                if(!err)console.log(res);                else                console.fault(err);  });              

Run the code.

$ node index.js
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed practice 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 two 0MBto check the performance of readFileSync, readFileand createReadStream .

The average retentiveness consumption of VS Code is 600-700MB in my automobile.

This is a screenshot before running any of the commands.

How to read files with Node.js

readFileSync

Check the screenshot. This operation took 373MB and it went on to upto ~450MB .

readFileSync

readFile (Asynchronous)

Cheque the screenshot. This operation took 506MB and information technology went on to upto ~600MB.

readFile (Asynchronous)

createReadStream

Bank check the screenshot. This performance took 287MB and it reached upto  ~300MB.

createReadStream

Conclusion

Node.js provides multiple methods to read a file. It 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 functioning may vary from machine to machine and file size. One must note that what we have demonstrated is just for the sake of a demo, so this must non be taken to be the concluding words. In that location are other npm packages bachelor for file system, for case,fs-extra.

Hope this tutorial has helped. Taking a formal training grade in Node.js would be a great way to fast-track your career.

Happy coding!

Tired of fixing bugs? Notice like shooting fish in a barrel 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

cooperyind1972.blogspot.com

Source: https://www.knowledgehut.com/blog/web-development/read-files-nodejs

0 Response to "How to Read From a File Nodejs"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel