Categories
JavaScript Answers

How to wait for a child process to finish in Node.js?

To wait for a child process to finish in Node.js, we listen for the exit event.

For instance, we write

const child = require("child_process").exec("python celulas.py");

child.stdout.pipe(process.stdout);
child.on("exit", () => {
  process.exit();
});

to call on with 'exit' to listen for the exit event, which is emitted when the process is finished.

Categories
JavaScript Answers

How to fix create-react-app, installation error (“command not found”) with JavaScript?

To fix create-react-app, installation error ("command not found") with JavaScript, we run npx.

For instance, we run

npx create-react-app app_name

to create a React project with name app_name with npx create-react-app without installing create-react-app locally.

Categories
JavaScript Answers

How to find the a referring sites URL in Node?

To find the a referring sites URL in Node, we call the req.headers.referer property.

For instance, we write

const referrer = req.headers.referer;

to get the referrer with the req.headers.referer property.

Categories
JavaScript Answers

How to create and read session with Node Express?

To create and read session with Node Express, we set the req.session property.

For instance, we write

req.session.email = req.param("email");

to set req.session.email to the req.param value to store the value in the session.

Categories
JavaScript Answers

How to fix Node fs.createWriteStream does not immediately create file?

To fix Node fs.createWriteStream does not immediately create file, we call write to write the file content.

For instance, we write

const tempFile = fs.createWriteStream(tempFilepath);

tempFile.on("open", (fd) => {
  http.request(url, (res) => {
    res
      .on("data", (chunk) => {
        tempFile.write(chunk);
      })
      .on("end", () => {
        tempFile.end();
        fs.renameSync(tempFile.path, filepath);
        return callback(filepath);
      });
  });
});

to create the tempFile write stream with createWriteStream.

And then we call res.on to listen for the data event to get the data.

We call tempFile.write with chunk to write the chunk to the write stream.

And we call tempFile.end to stop writing when the end event is emitted, which happens when all the data is received.