Read contents of a file and print it to console using javascript
16,035
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
Author by
Omiye Jay Jay
I am still a novice in programming, but I am really interested and hope to get very better.
Updated on July 12, 2022Comments
-
Omiye Jay Jay almost 2 years
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); } );