Categories
JavaScript Answers

How to fix Cannot find module for a Node app running in a Docker compose environment?

To fix Cannot find module for a Node app running in a Docker compose environment, we’ve to install the dependencies.

To do this, we write

FROM node:boron

# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

# Install app dependencies
COPY package.json /usr/src/app/
RUN npm install

# Bundle app source
COPY . /usr/src/app

EXPOSE 8080
CMD [ "npm", "start" ]

to run npm install with RUN npm install to install the dependencies in our Dockerfile.

Categories
JavaScript Answers

How to send flash messages in Node Express 4.0?

To send flash messages in Node Express 4.0, we use the flash package.

To add it, we write

app.use(flash());

Then we send a flash message in our middleware with

req.flash("signupMessage", anyValue);

The first argument is the key and the 2nd is the value.

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.