Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
}
);
like image 394
Omiye Jay Jay Avatar asked Aug 01 '13 23:08

Omiye Jay Jay


People also ask

How do you print to console in JavaScript?

You should use the console. log() method to print to console JavaScript. The JavaScript console log function is mainly used for code debugging as it makes the JavaScript print the output to the console. To open the browser console, right-click on the page and select Inspect, and then click Console.

How do you print the contents of a function to the console?

log() is a function in JavaScript that is used to print any kind of variables defined before in it or to just print any message that needs to be displayed to the user. Syntax: console. log(" ");

What is the JavaScript syntax for printing value in console?

What is the JavaScript syntax for printing values in Console? Explanation: The action which is built into the console object is the . log() method.


1 Answers

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
like image 71
Paul Sweatte Avatar answered Oct 24 '22 12:10

Paul Sweatte