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.

Categories
JavaScript Answers

How to fix Error: Failed to lookup view in Node Express?

To fix Error: Failed to lookup view in Node Express, we should use a valid path.

For instance, we write

const path = require("path");
app.use(express.static(path.join(__dirname + "../public")));

to call express.static foplder with the path returned by path.join to get the path of the /public folder one level above __dirname to expose the folder as the static files folder.

Categories
JavaScript Answers

How to fix webpack command not working with JavaScript?

To fix webpack command not working with JavaScript, we add the webpack command to a script.

For instance, we write

{
  "scripts": {
    "build": "webpack --config webpack.config.js"
  }
}

in package.json to add the build script.

We set it to run the webpack command with the webpack.config.js config.

Categories
JavaScript Answers

How to set ObjectId as a data type in Node Mongoose?

To set ObjectId as a data type in Node Mongoose, we set the value to ObjectId.

For instance, we write

const mongoose = require("mongoose");

const Schema = mongoose.Schema,
  ObjectId = Schema.ObjectId;

const SchemaProduct = new Schema({
  categoryId: ObjectId,
  title: String,
  price: Number,
});

to set the categoryId property to ObjectId to make categoryId an object ID field.