I need a little bit help how I can handle following task in JavaScript: I have an app, that use Jimp for image processing and node-sprite-generator. That all runs in node.js context. I load a few images to Jimp, make something with the image then write it back to my file system with the nodejs filemodule. Then I would take the new created images and pasted it to node-sprite-generator. The problem is, that not all images are created/written at this time. While the code for create the spritesheet runs immediately after Jimp returns, I think Jimp processing all of the images and return a promise. The result is, that the code for creating the spritesheet get executed but the stack is not done.
I tried to test if the file is written, with fs.stat() and the propertie mtime like
if (stat.mtime.getTime() === prev.mtime.getTime())
But then it can happens, that an error occurred, when the file is not created at this time. Also: I need a way to check if the image is written completely with handling, when the path to the image is current not available.
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!');
})
I think first I must check if the image exist at a given path and then check if written is finished. But when I make a fn with fs.access(path[, mode], callback) and the file is not created at this time, I get an error.