Read contents of a file and print it to console using javascript

file, javascript, node.js

Solution

Use the `readFile` method of the `fs` object to read the file, then use `console.log` to print it:

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

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

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

For instance, if it is named `loadfiles.js`, run it as such:

node loadfiles.js

Problem

I am new to javascript and I would like to specify a javascript program to read from a file and print the contents of the file to a console?.This is the code I have written below and am getting an error,please what's wrong with it? ``` var express = require('express'); var app = express.createServer(express.logger()); app.get('/',function(request,response){ var fs = require('fs'); var buffer = new Buffer(fs.readFileSync('index.html','utf8')); response.send(Buffer.toString()); }); var port = process.env.PORT || 5000; app.listen(port,function() { fs.readFileSync(); console.log("Listening on"+ port); } ); ```

Original source