Categories
JavaScript Answers

How to change the cache path for npm (or completely disable the cache) on Windows?

To change the cache path for npm (or completely disable the cache) on Windows, we run the config set cache command.

For instance, we run

> npm config set cache C:\dev\nodejs\npm-cache --global 

to set the cache directory to the C:\dev\nodejs\npm-cache folder.

We then run

npm --global cache verify

to verify the cache directory is set.

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.