检查文件是否完全用node.js写入

时间:2016-10-12 16:16:53

标签: javascript node.js

我需要一些帮助,以便我可以在JavaScript中处理以下任务: 我有一个使用Jimp的应用 用于图像处理和节点精灵生成器。这一切都在node.js上下文中运行。我将一些图像加载到Jimp,使用图像制作一些东西,然后使用nodejs filemodule将其写回我的文件系统。然后我将采用新创建的图像并将其粘贴到node-sprite-generator。问题是,此时并非所有图像都是创建/写入的。虽然在Jimp返回后立即运行创建spritesheet的代码,但我认为Jimp会处理所有图像并返回一个promise。结果是,创建spritesheet的代码被执行但堆栈没有完成。

我尝试测试文件是否写入,fs.stat()和属性mtime如

 if (stat.mtime.getTime() === prev.mtime.getTime())

但是,当此时未创建文件时,可能会发生错误。另外:当图像的路径当前不可用时,我需要一种方法来检查图像是否完全用处理写入。

function resize(img) {
    Jimp.read(img.path).then(function (err, file) {
        if (err) throw err;
        file.resize(200, 200)
            .quality(70)
            .write(newPath); //newPath for simplicity
    });
}


function rec(imgObjArray) {
    if(_.isEmpty(imgObjArray)) return;  
    resize(imgObjArray.pop());
//correct mistake in function call from fn() to rec()
    rec(imgObjArray);
}

rec(imgObjArray); //imgObjArray === [img,img,img....]

//nsg() does not work because not all images are written at this time
     nsg({
            src: [
                'out/images/desktop/*.jpg'
            ],
            spritePath: 'out/images/desktop/sprite.jpg',,
            compositor: 'jimp'
        }, function (err) {
            console.log('Sprite generated!');
        })

我认为首先我必须检查图像是否存在于给定路径,然后检查写入是否完成。但是当我使用fs.access(path [,mode],callback)创建一个fn并且此时没有创建文件时,我收到一个错误。

1 个答案:

答案 0 :(得分:3)

这里有混合的同步和异步代码。我将尝试描述评论中发生的事情:

首先,您的函数定义 - 您在没有正确处理其完成的情况下触发异步操作

// I've re-spaced the code slightly and removed your comments so mine stand out
function resize(img) {
    Jimp.read(img.path).then(function (err, file) {
        // this code only executes after the file is done reading, but this
        // is an asynchronous action - it doesn't hold up execution
        if (err) throw err;
        file.resize(200, 200).quality(70).write(newPath);
        // .write() is presumably *also* an asynchronous action - if you want
        // something to happen only *after* it's been written, it needs to be in
        // a callback or promise on the write method
    });

    // I added this explicitly - after you *start* your Jimp.read, you *immediately*
    // return from this function, *before* the read is completed.  If you want
    // something to happen only *after* your read and write, you either need to
    // return the promise so you can act on it, or put the further actions in a callback
    return undefined;
}

function rec(imgObjArray) {
    if(_.isEmpty(imgObjArray)) return; 
    // resize() runs and returns *before* the file is read, resized, and written
    resize(imgObjArray.pop());
    // I don't know what fn() is, it's not defined here - presumably it's not important
    fn(imgObjArray);
}

...然后,您的程序调用:

// this fires off and completes immediately, having initiated the asynchronous methods
rec(imgObjArray);

// you call this on the assumption that all of your code above has completed, but since
// it's asynchronous, that's not true, you get here with *none* of your images completed
nsg({
    src: [
        'out/images/desktop/*.jpg'
    ],
    spritePath: 'out/images/desktop/sprite.jpg',
    compositor: 'jimp'
}, function (err) {
    console.log('Sprite generated!');
});

您有两种选择:

如果file.write()是同步通话,您只需返回保证并对其采取行动:

function resize(img) {
    // by *returning* this call, we're actually returning the promise, we can act on
    // in the future
    return Jimp.read(img.path).then(function (err, file) {
        if (err) throw err;
        file.resize(200, 200).quality(70).write(newPath);
    });
}

function rec(imgObjArray) {
    if(_.isEmpty(imgObjArray)) return; 
    // the result of resize is now a promise
    return resize(imgObjArray.pop()).then(function(err) {;
        // again, assuming `fn()` is synchronous...
        fn(imgObjArray);
    });
}

// now the result of *this* call is a promise, which you can use to control
// the timing of your next call
rec(imgObjArray).then(function(err) {
    // now this will only run after all of the previous calls have executed
    nsg({
        src: [
            'out/images/desktop/*.jpg'
        ],
        spritePath: 'out/images/desktop/sprite.jpg',
        compositor: 'jimp'
    }, function (err) {
        console.log('Sprite generated!');
    });
});

...如果promise语法不正确,我会道歉,因为它们无处不在,所以我没有主动使用节点。

即使您的子调用是异步的,也有可能以相同的方式使用promises,我只是没有准备好。

否则,您可以将回调传递给您的函数:

function resize(img, cb) {
    // ... you get the idea...
        file.resize(200, 300).quality(70).write(newPath, cb);
}

function rec(imgObjArray, cb) {
    // ... you get the idea...
    resize(imgObjArray.pop(), cb);
}

rec(imgObjArray, function(err, response) {
    nsg({
        src: [
            'out/images/desktop/*.jpg'
        ],
        spritePath: 'out/images/desktop/sprite.jpg',
        compositor: 'jimp'
    }, function (err) {
        console.log('Sprite generated!');
    });
});

希望这有帮助!