节点v4.2.6
我有一个小程序:
var chokidar = require('chokidar');
var _ = require('lodash');
var q = require('q');
var fs = require('fs');
var faker = require('faker');
var file = 'testfile.txt';
var pending = '';
var writer;
fs.open(file,'w+',function(){
writer = fs.createWriteStream(file);
writer.on('error',function(err){
console.log(err);
});
writer.on('drain',rewrite);
var timer = setInterval(write(),100);
});
function write(){
var data = faker.Helpers.createCard();
console.log('attempting to write ' + Buffer.byteLength(data,'utf8') + ' bytes');
var ok = writer.write(data.toString());
if(!ok){
console.log('buffer full, saving in memory');
pending += data;
}else{
console.log('written');
}
}
function rewrite(){
console.log('buffer empty, writing ' + Buffer.byteLength(data,'utf8') + ' bytes from memory');
var ok = writer.write(pending);
if(!ok){
console.log('buffer full again. Saving in memory again');
pending += data;
}
}
将前几个字节写入文件后,错误输出:
timers.js:275
timer._repeat();
^
TypeError: timer._repeat is not a function
at wrapper [as _onTimeout] (timers.js:275:11)
at Timer.listOnTimeout (timers.js:92:15)
出了什么问题,我该如何纠正?
答案 0 :(得分:17)
此:
var timer = setInterval(write(),100);
传递write()
的结果作为每100毫秒调用一次的函数。 write()
没有返回函数(隐式返回undefined
),因此您获得TypeError
。相反,传递函数本身:
var timer = setInterval(write,100);