Asynchronously Read from Files

suggest change

Use the filesystem module for all file operations:

const fs = require('fs');

With Encoding

In this example, read hello.txt from the directory /tmp. This operation will be completed in the background and the callback occurs on completion or failure:

fs.readFile('/tmp/hello.txt', { encoding: 'utf8' }, (err, content) => {
  // If an error occurred, output it and return
  if(err) return console.error(err);

  // No error occurred, content is a string
  console.log(content);
});

Without Encoding

Read the binary file binary.txt from the current directory, asynchronously in the background. Note that we do not set the ‘encoding’ option - this prevents Node.js from decoding the contents into a string:

fs.readFile('binary.txt', (err, binaryContent) => {
  // If an error occurred, output it and return
  if(err) return console.error(err);

  // No error occurred, content is a Buffer, output it in
  // hexadecimal representation.
  console.log(binaryContent.toString('hex'));
});

Relative paths

Keep in mind that, in the general case, your script can be run with an arbitrary current working directory. To address a file relative to the current script, use __dirname (this assumes const path = require('path')):

fs.readFile(path.resolve(__dirname, 'someFile'), (err, binaryContent) => {
  // Rest of function
});

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents