Categories
JavaScript Answers

How to wait till element is displayed with Node Selenium WebDriver?

To wait till element is displayed with Node Selenium WebDriver, we use the wait method.

For instance, we write

const el = await driver.findElement(By.id(`import-file-acqId:${acqId}`));
await driver.wait(until.elementIsVisible(el), 100);
await el.sendKeys(file);

to call findElement with By.id(import-file-acqId:${acqId}) to find the element by ID.

Then we call wait with until.elementIsVisible(el) to wait for the element.

The timeout is set to 100ms.

Then we call sendKeys to press a key.

Categories
JavaScript Answers

How to read remote file with Node.js http.get?

To read remote file with Node.js http.get, we create a write stream.

For instance, we write

const fs = require("fs");
const https = require("https");

const file = fs.createWriteStream("data.txt");

https.get("https://www.w3.org/TR/PNG/iso_8859-1.txt", (response) => {
  const stream = response.pipe(file);

  stream.on("finish", () => {
    console.log("done");
  });
});

to call createWriteStream to create a write stream to write to data.txt.

Then we call get to make a get request to the file.

We get the response as a read stream and call pipe to pipe it to the file write stream.

And we call on to listen to the finish event which is emitted when writing is done.

Categories
JavaScript Answers

How to base64 encode a JavaScript object?

To base64 encode a JavaScript object, we convert it to a JSON string and base64 encode that.

For instance, we write

const obj = { a: "a", b: "b" };
const encoded = btoa(JSON.stringify(obj));
const actual = JSON.parse(atob(encoded));

to call JSON.strignify to convert obj to a JSON string.

Then we call btoa to convert the JSON string into a base64 string.

And we convert the base64 string back to an object with atob and JSON.parse.

Categories
JavaScript Answers

How to install Node in Dockerfile?

To install Node in Dockerfile, we run curl and apt-get.

For instance, in our Dockerfile, we write

RUN curl -sL https://deb.nodesource.com/setup_12.x | bash - 
RUN apt-get install -y nodejs

to download the Node setup script with curl and run it with bash.

And then we run apt-get to install nodejs.

Categories
JavaScript Answers

How to fix Node error: SyntaxError: Unexpected token import?

To fix Node error: SyntaxError: Unexpected token import, we can use CommonJS modules.

For instance, we write

const calc = require("./calc");
const { add, multiply } = calc;

to call require to include the calc.js module file.

And then we get the add and multiply properties from the object we set as the value of module.exports in calc.js.