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);
}
);
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.
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 values in Console? Explanation: The action which is built into the console object is the . log() method.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With