What is the difference between readFile and createReadStream in Node.js?

CWC
3 Min Read

Node.js is a runtime system that has become popular with most coders and is used mostly for developing server-side applications. Node.js is best known for creating real-time APIs and building a new matrix of interoperability across the web. There are two ways in which a file can be read and sent for execution in Node.js; readFile and CreateStream. Before exploring the difference between the two; let’s get to know more about Node.js itself and how it works.

How It Works

It’s important to note that Node.js isn’t a JavaScript framework. There are several frameworks that have been sufficiently written for Node.js such as; Restify.js, Express.js, and Hapi.js. Basically, Node.js is a highly customizable, stripped-down server engine that acts as a proto- server. This proto-server works in a loop and is ready to accept & respond to various requests. Any of those requests (on their own) may initialize other requests to different parts of the system; such as to read a given file off a disk or to send signals to spin a motor. That very loop is what is known as, “runtime” part.

Differences

While the fs.readfile loads the whole file into the memory you pointed out, the fs.createReadStream, on the other hand, reads the entire file in chunks of sizes that you specified. The client will also receive the data faster with fs.createReadStream since it is sent in chunks while it’s being read. The fs.readfile, however, reads the whole file first before it’s sent to the client. This can be negligible if the file size is small, but makes such a great difference where the disks are slow and the file content isbig.

Node.js will also find it easy to clean up the non-used memory with fs.readfile as compared to that of fs.createReadStream. The challenge of using the readFile is that it’ll not scale the available requests at a given time and will try loading all of them at once.

CreateReadstream, will, however, pipe the file content directly to the HTTP response object and this is time-saving.

[vc_row][vc_column][td_block_21 separator=”” tag_slug=”node-js” limit=”40″ tdc_css=””][/vc_column][/vc_row]

TAGGED:
Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

English
Exit mobile version