2

只是为了测试,我想每两秒创建一个文件,它设法创建了第一个文件,但在 2 秒后我得到以下错误:

Restify listening on port 8080 in %s mode
 create 2012_8_5_8_57.txt

timers.js:234
    callback.apply(timer, args);
         ^
TypeError: Cannot call method 'apply' of undefined
at Timer.exports.setInterval.timer.ontimeout (timers.js:234:14)

一切都在带有 restify 框架的节点服务器中运行。如果有人知道该错误将非常感谢您的帮助!这是代码:

var d = new Date();
var n = d.getDay();
var m = d.getMonth();
var y = d.getFullYear();
var min = d.getMinutes();
var sec = d.getSeconds();

//create file
function openUnlink(name) {
    console.log(name);
    fs.open(name, 'w', function (err) {
        console.log(' create ' + name);

    });

};

function createFile() {
    openUnlink(y+'_'+m+'_'+n+'_'+min+'_'+sec+'.txt');
};

//create file every 2 seconds
setInterval(createFile(), 2000);
4

1 回答 1

4

您不需要在setInterval. 您只需要传递对它的引用。您还需要在createFile函数内部定义日期。

var fs = require('fs');

//create file
function openUnlink(name) {
    console.log(name);
    fs.open(name, 'w', function (err) {
        console.log(' create ' + name);

    });

};

function createFile() {
    var d = new Date();
    var n = d.getDay();
    var m = d.getMonth();
    var y = d.getFullYear();
    var min = d.getMinutes();
    var sec = d.getSeconds();
    openUnlink(y+'_'+m+'_'+n+'_'+min+'_'+sec+'.txt');
};

//create file every 2 seconds
setInterval(createFile, 2000);
于 2012-09-07T08:45:42.577 回答