0

I'm trying to build a certificate generation module using nodeJS.
The api to create certificate is as follows

// Create certificate

const express = require('express');
const router = express.Router();
const { createCanvas } = require('canvas')
const fs = require("fs");
const { decodeBase64Image } = require('../helper/certificatehelper');

router.post('/imageadd', async (req, res, next) => {
  try {

    const { name } = req.body;
    
    const width = 1920
    const height = 1080

    const canvas = createCanvas(width, height)
    const context = canvas.getContext('2d')
    context.fillStyle = "white";
    context.fillRect(0, 0, width, height)

    context.fillStyle = '#000'
    context.font = "72px Arial";
    context.textAlign = "center";
    context.fillText(name, 900, 500);

    const dataurl = canvas.toDataURL();

    const decodedImg = decodeBase64Image(dataurl);
    const imageBuffer = decodedImg.data;
    
    fs.writeFileSync(`./src/images/image1.png`, imageBuffer);

    fs.readFile('./src/images/image1.png', function(err, data) {
      if (err) throw err; // Fail if the file can't be read.
        res.writeHead(200, {'Content-Type': 'image/jpeg'});
        res.end(data); // Send the file data to the browser.
    });

    res.json({ data: respArray, success: true, msg: 'Certificate generated' });
  } catch (error) {
    res.json({ success: false, msg: error.message });
  }
})


module.exports = router;

The problem I'm facing is, If multiple request are send in parallel how do I generate one certificate at a time (synchronized).
Other requests need to wait till the certificate is generated for previous request.
The certificates should be generated in a separate process from the main app process.
How do I solve the above given problem.

sheetaldharerao
  • 482
  • 3
  • 11
  • Does this answer your question? [How to implement a lock in JavaScript](https://stackoverflow.com/questions/5346694/how-to-implement-a-lock-in-javascript) – Ayush Gupta Aug 09 '21 at 06:32
  • First of all, you shouldn't use `writeFileSync` on the server because it's blocking. Furthermore you seem to send multiple responses (a json and a buffer) which won't work. And actually I don't get it, why multiple parallel requests would be a problem? You don't need to write a file at all (the hardcoded filename would be indeed a problem). Just use in memory buffers – derpirscher Aug 09 '21 at 06:57

0 Answers0