Categories
JavaScript Answers

How to wait N seconds before continuing to the next line with Puppeteer and JavaScript?

To wait N seconds before continuing to the next line with Puppeteer and JavaScript, we use the waitForTimeout method.

For instance, we write

await page.waitForTimeout(4000);

to call page.waitForTimeout to pause the program for 4 seconds.

Categories
JavaScript Answers

How to detect CTRL+C in Node.js?

To detect CTRL+C in Node.js, we can listen for the SIGINT event.

For instance, we write

process.on("SIGINT", () => {
  console.log("Caught interrupt signal");

  if (shouldExit) {
    process.exit();
  }
});

to listen for the SIGIN event with process.on.

We call it with a callback that’s called when ctrl+c is pressed.

In it, we call process.exit to exit the program if shouldExit is true.

Categories
JavaScript Answers

How to fix AWS lambda API gateway error “Malformed Lambda proxy response” with JavaScript?

To fix AWS lambda API gateway error "Malformed Lambda proxy response" with JavaScript, we should return a response in the right format.

For instance, our response should have something like

{
  "isBase64Encoded": true,
  "statusCode": 200,
  "headers": { "headerName": "headerValue" },
  "body": "..."
}

The properties listed should be in the response JSON.

statusCode is the HTTP status code.

headers is an object with the response headers keys and values.

body is the response body.

Categories
JavaScript Answers

How to specify path to node_modules in package.json with Node.js?

To specify path to node_modules in package.json with Node.js, we set the NODE_PATH environment variable.

For instance, we run

export NODE_PATH=/your/dir/node_modules

to set the NODE_PATH to the /your/dir/node_modules folder to specify that as the package folder for the project.

Then when we run our app, the packages will be imported from this folder.

Categories
JavaScript Answers

How to use Node.js require inside TypeScript file?

To use Node.js require inside TypeScript file, we call require with import or use the import statement.

For instance, we write

import sampleModule = require("module-name");

to require the module-name module with require and import.

Or we write

import * as sampleModule from "module-name";

to import the module-name module as a default import.