Categories
JavaScript Answers

How to write an array to file with Node.js?

To write an array to file with Node.js, we call the writeFile method.

For instance, we write

require("fs").writeFile("./my.json", JSON.stringify(myArray), (err) => {
  if (err) {
    console.error("error");
  }
});

to call writeFile with the file path and a stringified version of the myArray array to write the content of myArray into the my.json file.

Categories
JavaScript Answers

How to execute PHP scripts within Node.js web server?

To execute PHP scripts within Node.js web server, we call the exec function.

For instance, we write

const exec = require("child_process").exec;

app.get("/", (req, res) => {
  exec("php index.php", (error, stdout, stderr) => {
    res.send(stdout);
  });
});

to call exec to run index.php with php.

We get the output from the stdout parameter in the callback.

Categories
JavaScript Answers

How to brew install specific version of Node?

To brew install specific version of Node, we run a few brew commands.

To do this, we run

brew install node@14
brew unlink node
brew link node@14

to install Node 14 with brew install.

And then we remove the old version of node with brew unlink.

Then we run brew link to link Node 14 as the default node version.

Categories
JavaScript Answers

How to download a file to disk from an AWS S3 bucket with Node?

To download a file to disk from an AWS S3 bucket with Node, we call the getObject method.

For instance, we write

const s3 = new AWS.S3();
const s3Params = {
  Bucket: "your bucket",
  Key: "path/to/the/file.ext",
};

s3.getObject(s3Params, (err, res) => {
  if (err === null) {
    res.attachment("file.ext");
    res.send(data.Body);
  } else {
    res.status(500).send(err);
  }
});

to call the getObject method with the Bucket and Key of the item to get.

We get the data from the data.Body property.

Categories
JavaScript Answers

How to get name and line of calling function in Node.js?

To get name and line of calling function in Node.js, we use the error’s stack property.

For instance, we write

console.log("DEBUG", new Error().stack.split("at ")[1].trim());

to create an Error object and use its stack property to get the name and line of the calling function.