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.

Categories
JavaScript Answers

How to fix await not waiting for promise with JavaScript async function?

To fix await not waiting for promise with JavaScript async function, we use await on a promise.

For instance, we write

const func = async () => console.log(await getResult());

to call getResult to return a promise.

And then we use await to get the resolve value of the returned promise.

Categories
JavaScript Answers

How to set request header when making connection with JavaScript socket.io-client?

To set request header when making connection with JavaScript socket.io-client, we set the extraHeaders property.

For instance, we write

const socket = io("http://localhost", {
  extraHeaders: {
    Authorization: "Bearer authorization_token_here",
  },
});

to set extraHeaders to an object with the header keys-value pairs.

Categories
JavaScript Answers

How to get Node.js Express to listen only on localhost?

To get Node.js Express to listen only on localhost, we call listen with the port only.

For instance, we write

app.listen(3001);

to only listen to port 3001 on localhost for requests.