How to wait for the file to get created before sending request back to client using res.sendFile()

I have a file creator block which writes the file to disk, and then sends the file to the client.

But the response is sent before the file is getting written.

  carbone.render("./template.odt", data, options, (err, ress) => {
    if (err) {
      return console.log(err);
    var paths = `./static/reports/report-${timestamp}.pdf`;
    fs.writeFileSync(paths, ress);

    path.join(__dirname, "..", "static", "reports", `report-${timestamp}.pdf`)

What is the solution so that sendFile waits for the file to be written and then fetches it?


This is what the callback function is for. carbone.render renders a template and when it’s done returns result to the callback function. JS will not wait for the carbone.render to complete before moving to res.sendFile. You can move the sending part inside the callback function.