Categories
JavaScript Answers

How to use while loop with promises with JavaScript?

To use while loop with promises with JavaScript, we use async and await.

For instance, we write

const loop = async (value) => {
  let result = null;
  while (result !== "ok") {
    console.log(value);
    result = await doSomething(value);
  }
};

to define the loop function.

In it, we use a while loop that runs until result isn’t 'ok'.

In the loop, we call doSomething which returns a promise and we use await to wait for the promise to finish and return the resolved value.

We set the resolved value to result.

Categories
JavaScript Answers

How to upload a file to Amazon S3 with Node.js?

To upload a file to Amazon S3 with Node.js, we call the putObject method.

For instance, we write

const AWS = require("aws-sdk");
AWS.config.update({
  accessKeyId: "accessKeyId",
  secretAccessKey: "secretAccessKey",
  region: "region",
});

const params = {
  Bucket: "yourBucketName",
  Key: "someUniqueKey",
  Body: "someFile",
};
try {
  const uploadPromise = await new AWS.S3().putObject(params).promise();
  console.log("Successfully uploaded data to bucket");
} catch (e) {
  console.log("Error uploading data: ", e);
}

to call update to connect to AWS.

Then we call putObject with an object with the Bucket, Key and Body to start the upload.

And then we use await to wait for the promise to finish running.

Categories
JavaScript Answers

How to verify if Node.js instance is dev or production?

To verify if Node.js instance is dev or production, we get the NODE_ENV environment variable value.

For instance, we write

const env = process.env.NODE_ENV || "development";

to get the NODE_ENV environment variable value with process.env.NODE_ENV.

Categories
JavaScript Answers

How to spawn and kill a process in Node.js?

To spawn and kill a process in Node.js, we use the tree-kill package.

For instance, we write

const kill = require("tree-kill");
const spawn = require("child_process").spawn;

const scriptArgs = ["myScript.sh", "arg1", "arg2", "youGetThePoint"];
const child = spawn("sh", scriptArgs);

button.on("someEvent", () => {
  kill(child.pid);
});

to call spawn to run the 'sh' command with the scriptArgs command line arguments.

And then we call kill to kill the process with the child.pid process ID.

Categories
JavaScript Answers

How to fix Node cannot find module “fs” when using Webpack?

To fix Node cannot find module "fs" when using Webpack, we set target to 'node'.

For instance, in webpack.config.js, we write

module.exports = {
  entry: "./app",
  output: {
    path: __dirname,
    filename: "bundle.js",
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: "node_modules",
        loader: "babel",
        query: { presets: ["es2015"] },
      },
    ],
  },
  target: "node",
};

to set target to 'node' to make Webpack build for Node.js instead of browser.