Categories
JavaScript Answers

How to read keystrokes from stdin with Node.js?

To read keystrokes from stdin with Node.js, we can listen for keypresses with raw mode.

For instance, we write

const stdin = process.openStdin();
require("tty").setRawMode(true);

stdin.on("keypress", (chunk, key) => {
  process.stdout.write("Get Chunk: " + chunk + "\n");
  if (key && key.ctrl && key.name === "c") {
    process.exit();
  }
});

to set raw mode to true with setRawMode.

We open stdin with openStdin.

And we listen for the keypresses by calling on with 'keypress'.

We get the key pressed with key.

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.