[英]Node: How to read file?
I want to read a file and return is as a response to GET
request 我想读取文件并返回作为对GET
请求的响应
This is what I am doing 这就是我在做什么
app.get('/', function (request, response) {
fs.readFileSync('./index.html', 'utf8', function (err, data) {
if (err) {
return 'some issue on reading file';
}
var buffer = new Buffer(data, 'utf8');
console.log(buffer.toString());
response.send(buffer.toString());
});
});
index.html
is index.html
是
hello world!
When I load page localhost:5000
, the page spins and nothing happens, what is I am doing incorrect here 当我加载页面localhost:5000
,页面旋转并且什么也没有发生,这是我在做什么错
I am newbie to Node. 我是Node的新手。
You're using the synchronous version of the readFile
method . 您正在使用readFile
方法的同步版本。 If that's what you intended, don't pass it a callback. 如果这正是您的意图,请不要将其传递给回调函数。 It returns a string (if you pass an encoding): 它返回一个字符串(如果您通过编码):
app.get('/', function (request, response) {
response.send(fs.readFileSync('./index.html', 'utf8'));
});
Alternatively (and generally more appropriately) you can use the asynchronous method (and get rid of the encoding, since you appear to be expecting a Buffer
): 另外(通常更合适),您可以使用异步方法(并摆脱编码,因为您似乎期望使用Buffer
):
app.get('/', function (request, response) {
fs.readFile('./index.html', { encoding: 'utf8' }, function (err, data) {
// In here, `data` is a string containing the contents of the file
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.