read a file and print the contents of the file in javascript

To read a file and print its contents in Node.js, you can use the built-in fs (file system) module. Here is an example code snippet:

const fs = require('fs');

fs.readFile('path/to/file.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});
131 chars
7 lines

In this code, we first import the fs module. We then use the fs.readFile() method to read the file at the specified file path. The second parameter specifies the file encoding (in this case, 'utf8'), which is necessary to read and output the file contents as a string.

The readFile() method takes a callback function as its third parameter, which is called after the file is read. If there is an error reading the file, the callback function will receive an error object (err). Otherwise, the file contents will be passed as the second parameter to the callback function (data in this example). We simply log the contents of the file to the console using console.log(), but you could do anything with the data variable at this point.

gistlibby LogSnag