Use Node to read files

How to use Node andfsModule

The easiest way to read files in Node is to usefs.readFile()Method, passing it the file path and the callback function (and error) that will be called together with the file data:

const fs = require('fs')

fs.readFile(’/Users/flavio/test.txt’, (err, data) => { if (err) { console.error(err) return } console.log(data) })

Or you can use the synchronized versionfs.readFileSync():

const fs = require('fs')

try { const data = fs.readFileSync(’/Users/flavio/test.txt’, ‘utf8’) console.log(data) } catch (err) { console.error(err) }

The default encoding is utf8, but you can use the second parameter to specify a custom encoding.

Bothfs.readFile()withfs.readFileSync()Before returning the data, please read all the contents of the file in the memory.

This means that large files will have a significant impact on your memory consumption and program execution speed.

In this case, a better option is to use a stream to read the contents of the file.

Download mine for freeNode.js manual


More node tutorials: