0

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);
    process.exit();
  });

  res.sendFile(
    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?

Arya Lisa
  • 5
  • 1
  • You are using `writeFileSync()` meaning the write was a sucess after that call. you can just return it after it – flx Aug 26 '21 at 07:08
  • I've tried adding the response right after `writeFileSync`, but it still doesn't send the file The server sends `Error: socket hang up` – Arya Lisa Aug 26 '21 at 07:13

2 Answers2

0

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.

  • removing the process.exit() and adding it inside the render function after the writeFileSync line worked. – Arya Lisa Aug 26 '21 at 07:22
0

You need to add sendFile code into callback function of carbone.render or else you can refer this question.

Bhavesh Mevada
  • 242
  • 1
  • 3
  • 14