【发布时间】:2018-03-25 18:20:30
【问题描述】:
我有这个功能:
app.get('/counter', function (req, res) {
console.log('/counter Request');
var counter = 0;
fs.readFile(COUNTER_FILE_NAME, function(err, data) {
counter = data;
});
console.log('Read Counter: ' + counter);
counter = counter + 1;
// delete old file
fs.unlink(COUNTER_FILE_NAME, function (err) {
if (err) console.log('Cant chagne old counter file');
});
fs.appendFile(COUNTER_FILE_NAME, counter, function (err) {
if (err) if (err) console.log('Cant create new counter file');
});
console.log('Change Counter To: ' + counter);
res.status(200);
res.writeHead('content-type','text/plain')
res.Send(counter);
})
由于未知原因,我收到以下错误:
TypeError: res.Send is not a function
我看了这篇文章: https://stackoverflow.com/questions/44176021/nodejs-res-send-is-not-a-function
它看起来像其他错误。
我该如何解决?
【问题讨论】:
-
这段代码还有其他问题。您需要等到
fs.readFile()完成后再继续使用counter值。您需要等到fs.unlink()完成后再调用fs.appendFile(),并且在完成之前发送您的响应。这段代码表明对 node.js 中的异步操作完全缺乏理解,并且无法正常工作。同样不清楚的是counter在你的文件中是一个字符串,在这种情况下counter + 1可能不会做你想做的事。 -
@jfriend00 是正确的,TypeError 是您最不必担心的。您的
readFile、unlink、appendFile都将几乎并行执行。欢迎来到异步编程的世界。 -
另外,这是什么:
if (err) if (err)?
标签: javascript node.js express