file_get_contents() equivalent for Node.JS

Kyle Hotchkiss picture Kyle Hotchkiss · Jan 8, 2012 · Viewed 17.1k times · Source

I was wondering if there was any file_get_contents() equivalents in Node.JS modules or elsewhere. It has to lock the process until the download is finished, so the existing request() code in Node.js won't work. While it doesn't need to read into the string, the locking, synchronous nature is important.

If this doesn't exist, is using CURL via the OS module an efficient way of handling the same process?

Answer

WildlyInaccurate picture WildlyInaccurate · Jul 19, 2013

fs.readFileSync appears to do what you're asking. From the manual:

fs.readFileSync(filename, [options])

Synchronous version of fs.readFile. Returns the contents of the filename.

If the encoding option is specified then this function returns a string. Otherwise it returns a buffer.