任何人都可以找出这个代码有什么问题吗?我试图写一小部分字节到一个文件,我得到的是一个零长度的文件,没有错误报告。为什么使用promise的异步IO生成一个零长度的文件?
我想在node.js中使用异步文件IO和bluebird promise来将一些数据写入本地文件。我已经使用回调函数成功编写了此函数的同步版本和异步版本。但是,因为回调版本嵌套在地狱里,并且有各种错误处理问题,并且不容易维护,所以我认为我会尝试使用promise的版本,因为这应该是它的优势(更好的错误处理,更少的嵌套,更容易顺序异步操作)。
不幸的是,承诺版本只导致零长度的文件。这里是承诺版本的代码:
// at initialization time
var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs'));
// code in a function
var header = new Buffer('[temperatures] {"formatVersion": "1", "fields": ["t", "atticTemp", "outsideTemp"]}\r\n');
filename += ".new";
console.log("async write started");
var fd;
fs.openAsync(filename, "w", 438).then(function(ffd) {
fd = ffd;
return fs.writeAsync(fd, header, 0, header.length, null);
}).then(function(args /* [written, buffer] */) {
var written = args[0];
console.log("bytes written =" + written);
if (written !== header.length) {
console.log("not all data written");
throw new Error("not all data written");
}
// lots more data to write here
return fs.closeAsync(fd);
}).then(function() {
fd = null;
console.log(" async write finished");
}).catch(function(e) {
// if (fd) fs.closeAsync(fd);
console.log(e, "data.writeData() - error writing data (new format)");
});
我已经做了一切我知道如何做调试。所有预期的console.log()
错误消息都以所需顺序显示。我已经验证了所有返回值和参数。没有任何错误报告。在再次运行之前,我已经删除了以前的文件。我在我的回调版本中使用了相同的参数和文件名,工作得很好(这似乎排除了文件权限问题)。我重新启动了电脑(顺便说一句,这是一个树莓派)。
我很难过。我认为这一定是愚蠢的,我在使用承诺时做错了,但我不能为了我的生活而看到什么是错的。
+1使用蓝鸟:) – simonzack 2014-09-06 04:23:41
这适用于我。你能使它更具可重复性吗? – simonzack 2014-09-06 04:32:28
@simonzack - 我必须看看我是否可以在独立的node.js应用程序中重现它。 – jfriend00 2014-09-06 04:52:41