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
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]