Categories
JavaScript Answers

How to fix the Express command not found error with JavaScript?

To fix the Express command not found error with JavaScript, we install the express-generator package.

To install it, we run

npm install -g express-generator

to install the express-generator package globally.

Categories
JavaScript Answers

How to fix ‘ts-node’ is not recognized as an internal or external command, operable program or batch file with JavaScript?

To fix ‘ts-node’ is not recognized as an internal or external command, operable program or batch file with JavaScript, we install the ts-node package.

To install it, we run

npm install -g ts-node

to install the ts-node package as a global package.

Categories
JavaScript Answers

How to wrap async function calls into a sync function in Node.js or JavaScript?

To wrap async function calls into a sync function in Node.js or JavaScript, we create a promise from it.

For instance, we write

const asyncOperation = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("hi");
    }, 3000);
  });
};

const asyncFunction = async () => {
  return await asyncOperation();
};

to create a new promise with the Promise constructor.

We call it with a callback that calls setTime with a callback that calls resolve to settle the promise.

Then we call the asyncOperation function and use await to get the argument we call resolve with.

Categories
JavaScript Answers

How to write JSON object to a JSON file with Node.js fs.writeFileSync?

To write JSON object to a JSON file with Node.js fs.writeFileSync, we call JSON.stringify.

For instance, we write

const fs = require("fs");
const content = JSON.stringify(output);

fs.writeFileSync("/tmp/phraseFreqs.json", content);

to call JSON.stringift to coinvert the output object to a JSON string.

Then we call writeFileSync with the path to write to and the stringified JSON object content to write the JSON to the file.

Categories
JavaScript Answers

How to see the SQL generated by Node Sequelize.js?

To see the SQL generated by Node Sequelize.js,. we set the logging option.

For instance, we write

const sequelize = new Sequelize("database", "username", "password", {
  logging: console.log,
});

to set the logging property to log with console.log.

We can also write

const sequelize = new Sequelize("database", "username", "password", {
  logging: (str) => {
    // do your own logging
  },
});

to log with our own logging function.