最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - Read contents of a file and print it to console using javascript - Stack Overflow

programmeradmin0浏览0评论

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);
}
);

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);
}
);
Share Improve this question edited Aug 3, 2013 at 15:33 falsetru 369k66 gold badges763 silver badges658 bronze badges asked Aug 1, 2013 at 23:23 Omiye Jay JayOmiye Jay Jay 4495 gold badges10 silver badges20 bronze badges 12
  • 1 Are you talking about Node? – user1726343 Commented Aug 1, 2013 at 23:25
  • possible duplicate of is it possible to read a file using javascript? – raina77ow Commented Aug 1, 2013 at 23:25
  • yes I am talking about node – Omiye Jay Jay Commented Aug 1, 2013 at 23:27
  • 1 no I havent done any research.Could you help please – Omiye Jay Jay Commented Aug 1, 2013 at 23:29
  • 1 "no I havent done any research.Could you help please": you must be new around here. that's not how we do things... – dandavis Commented Aug 1, 2013 at 23:36
 |  Show 7 more comments

1 Answer 1

Reset to default 14

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
发布评论

评论列表(0)

  1. 暂无评论