Categories
JavaScript Answers

How to press Enter button in JavaScript Puppeteer?

To press Enter button in JavaScript Puppeteer, we call the page.keyword.press method.

For instance, we write

await page.keyboard.press("Enter");

to call page.keyboard.press to press the enter key on the page.

Categories
JavaScript Answers

How to loop through an array without using array size with Node?

To loop through an array without using array size with Node, we use the forEach method.

For instance, we write

const myArray = ["1", "2", 3, 4];

myArray.forEach((value) => {
  console.log(value);
});

to call forEach with a callback that gets the entry in myArray being looped through.

We get the value being looped through from value.

Categories
JavaScript Answers

How to fix await is not working for Node request module?

To fix await is not working for Node request module, we switch to the node-fetch module.

To use it, we write

const url = "http://www.example.com";
try {
  const response = await fetch(url);
  const json = await response.json();
  return { message: json.message, status: json.type };
} catch (error) {
  console.log(error);
}

to call fetch with the url to make a get request to it.

It returns a promise so we can use await to get the response.

And then we use await again to get the response body returned by the promise returned by response.json.

Categories
JavaScript Answers

How to write to stdin from an already initialized process with Nodejs Child Process?

to write to stdin from an already initialized process with Nodejs Child Process, we call trhe stdin.write method.

For instance, we write

const spawn = require("child_process").spawn;
const child = spawn("phantomjs");

child.stdin.setEncoding("utf-8");
child.stdout.pipe(process.stdout);

child.stdin.write("console.log('Hello from PhantomJS')\n");

child.stdin.end();

to call stdin.write to write to stdin.

And then we stop writing with stdin.end.

Categories
JavaScript Answers

How to import from root with JavaScript?

To import from root with JavaScript, we use ~.

For instance, we write

import 'foo' from '~/components/foo.js';

to use ~ as the alias for the root folder when using import to import the foo module.