[英]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? 我是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);
}
);
Use the readFile
method of the fs
object to read the file, then use console.log
to print it: 使用
fs
对象的readFile
方法读取文件,然后使用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: 例如,如果将其命名为
loadfiles.js
, loadfiles.js
运行它:
node loadfiles.js
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.