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.

Categories
JavaScript Answers

How to read Excel file using Node.js?

To read Excel file using Node.js, we call the ExcelJS readFile method.

We install it by running

npm i exceljs

And we write

const ExcelJS = require("exceljs/dist/es5");
const workbook = new Excel.Workbook();
await workbook.xlsx.readFile(filename);

to create a workbook with the Workbook constructor.

Then we call readFile to read the filename file into the workbook.

Categories
JavaScript Answers

How to receive email in Node.js?

To receive email in Node.js, we use the mailin module.

To install it, we run

npm install --save mailin

Then we write

const mailin = require("mailin");

mailin.start({
  port: 25,
  disableWebhook: true,
});

mailin.on("authorizeUser", (connection, username, password, done) => {
  if (username === "johnsmith" && password === "mysecret") {
    done(null, true);
  } else {
    done(new Error("Unauthorized!"), false);
  }
});

mailin.on("startMessage", (connection) => {
  console.log(connection);
});

mailin.on("message", (connection, data, content) => {
  console.log(data);
});

to call mailin.start to start watching for emails.

And then we call on to listen for the 'authorizeUser', 'startMessage' and 'message' events.

The authorizeUser event is emitted when a user logs in.

The message event handler has the messages stored in data.