I'm trying to use the canvas
module to create a PNG file in a node.js script.
I have a file, image.js
that handles the image creation:
const { createCanvas, loadImage } = require('canvas');
const fs = require('fs');
function generateImage(param1, param2) {
const canvas = createCanvas(4096, 4096);
const ctx = canvas.getContext('2d');
// ...
return new Promise(function (resolve, reject) {
loadImage('base.png').then((image) => {
ctx.drawImage(image, 40, 40, 200, 200);
let out = fs.createWriteStream(__dirname + '/temp.png');
let stream = canvas.pngStream();
stream.on('data', function (chunk) {
out.write(chunk);
});
stream.on('end', function () {
console.log('saved png');
out.close(); // i probably don't need both, but neither seems to work properly...
out.end();
resolve();
});
});
});
}
module.exports = generateImage;
When I append generateImage('a', 'b');
at the end of this file and then run it separately (node image.js
), it works as expected and produces my image. However, when I try to call it from a different file (in the same folder), it seems like the file handle does not close, and the image on disk is an empty file while the script is running.
main.js
(simplified):
const generateImage = require('./image');
const fs = require('fs');
async function main() {
var stats = fs.statSync("temp.png");
console.log(stats["size"]); // output: 0, expected: > 0
}
generateImage("text", "text").then(() => main());
I'm new to node.js, so it's very possible that I'm missing something obvious.