Skip to content
Advertisement

Check if file is completely written with node.js

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

JavaScript

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.

JavaScript

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.

Advertisement

Answer

You’ve got a mix of synchronous and asynchronous code in here. I’ll try to describe what’s happening in comments:

First, your function definitions – you’re firing off asynchronous actions without properly handling their completions

JavaScript

… then, your procedural calls:

JavaScript

You have two options:

If file.write() is a synchronous call, you can just return the promise and act on it:

JavaScript

… apologies if the promise syntax is incorrect, I haven’t used node actively since they became ubiquitous.

There is likely a way to use promises in the same way even if your sub calls are asynchronous, I just don’t have that ready.

Otherwise, you can pass a callback into your functions:

JavaScript

Hope this helps!

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement