读取文件的内容并使用 javascript 将其打印到控制台

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18006282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:26:02  来源:igfitidea点击:

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

javascriptnode.jsfile

提问by Omiye Jay Jay

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?

我是 javascript 新手,我想指定一个 javascript 程序来读取文件并将文件的内容打印到控制台?。这是我在下面编写的代码,但出现错误,请问有什么问题?

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

回答by Paul Sweatte

Use the readFilemethod of the fsobject to read the file, then use console.logto print it:

使用对象的readFile方法fs读取文件,然后使用console.log打印:

/* 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:

例如,如果它是 named loadfiles.js,那么运行它:

node loadfiles.js