Share:- Whatsapp Facebook Facebook

------------------------------------- Welcome to Developerhelpway Q&A, where you can ask questions and receive answers from other members of the community.

Read contents of a file and print it to console using node.js

0 votes
31 views
Read contents of a file and print it to console using node.js
asked Dec 15, 2018 in Node.js by Upendra Diwakar

1 Answer

0 votes
To read file in node.js use fs module with readFile method. The readFile method of the fs object reads the file and print into console by using console.log.

/* Import File System Object */
var fs = require('fs');

/* Read File */
fs.readFile('test.json', bar)

function bar (error, data)  {
  /* If an error exists, show it, otherwise show the file */
  error ? Function("error","throw error")(error) : console.log(JSON.stringify(data) );
  };

The file named is fileReader.js.

To run it use following command: node fileReader.js
answered Dec 17, 2018 by ranju_12 (3,740 points)
...