Categories
JavaScript Answers

How to delete a folder on S3 with Node.js?

Sometimes, we want to delete a folder on S3 with Node.js.

In this article, we’ll look at how to delete a folder on S3 with Node.js.

How to delete a folder on S3 with Node.js?

To delete a folder on S3 with Node.js, we can use listObjectsV2 to list all objects in a bucket.

Then we call deleteObjects to delete the objects in the document.

For instance, we write

const emptyS3Directory = async (bucket, dir) => {
  const listParams = {
    Bucket: bucket,
    Prefix: dir
  };
  const listedObjects = await s3.listObjectsV2(listParams).promise();

  if (listedObjects.Contents.length === 0) {
    return;
  }

  const deleteParams = {
    Bucket: bucket,
    Delete: {
      Objects: []
    }
  };

  deleteParams.Delete.Objects = listedObjects.Contents.map(({
    Key
  }) => Key);
  await s3.deleteObjects(deleteParams).promise();
  if (listedObjects.IsTruncated) {
    await emptyS3Directory(bucket, dir);
  }
}

to define the emptyS3Directory that calls listObjectsV2 and promise to return a promise that returns all the file data in the bucket.

Then we define the deleteParams with the Delete.Objects property that we populate with

deleteParams.Delete.Objects = listedObjects.Contents.map(({
  Key
}) => Key);

to fill it with the keys to remove from the bucket.

And then we remove all the bucket contents with

await s3.deleteObjects(deleteParams).promise();

Finally, we check if the bucket is empty with listedObjects.IsTruncated.

And then we empty the bucket with

await emptyS3Directory(bucket, dir);

Conclusion

To delete a folder on S3 with Node.js, we can use listObjectsV2 to list all objects in a bucket.

Then we call deleteObjects to delete the objects in the document.

Categories
JavaScript Answers

How to wait for async actions inside AWS Lambda?

Sometimes, we want to wait for async actions inside AWS Lambda.

In this article, we’ll look at how to wait for async actions inside AWS Lambda.

How to wait for async actions inside AWS Lambda?

To wait for async actions inside AWS Lambda, we can return a promise from method that does async actions.

Then we can use await to wait for the action to complete.

For instance, we write

exports.handler = async (event) => {
  const uploadPromises = folder.files.map(file => {
    return s3.putObject({
      Bucket: "mybucket",
      Key: file.name,
      Body: file.data
    }).promise();
  });

  await Promise.all(uploadPromises);
  return 'exiting'
};

to call folder.files.map with a callback to return the promise returned by promise after calling putObject.

Then we call Promise.all with uploadPromises to run all the promises in parallel and wait for all of them to be done with await before running the return statement.

Conclusion

To wait for async actions inside AWS Lambda, we can return a promise from method that does async actions.

Then we can use await to wait for the action to complete.

Categories
JavaScript Answers

How to use the Mongoose findOne method?

Sometimes, we want to use the Mongoose findOne method.

In this article, we’ll look at how to use the Mongoose findOne method.

How to use the Mongoose findOne method?

To use the Mongoose findOne method, we call it with an object with the values we’re looking for and a callback that has the returned results.

For instance, we write

Auth.findOne({
  name
}, (err, obj) => {
  console.log(obj);
});

to call findOne to find entries with the name field set to name.

Then we get the returned result from the obj parameter in the callback.

Conclusion

To use the Mongoose findOne method, we call it with an object with the values we’re looking for and a callback that has the returned results.

Categories
JavaScript Answers

How to verify that an exception is thrown using Mocha and Chai and async and await?

Sometimes, we want to verify that an exception is thrown using Mocha and Chai and async and await.

In this article, we’ll look at how to verify that an exception is thrown using Mocha and Chai and async and await.

How to verify that an exception is thrown using Mocha and Chai and async and await?

To verify that an exception is thrown using Mocha and Chai and async and await, we can use the chai-as-promised package.

We install it by running

npm i chai-as-promised

Then we can use it by writing

const chai = require('chai')
const {
  expect
} = chai
chai.use(require('chai-as-promised'))

const wins = async () => {
  return 'Winner'
}

const fails = async () => {
  throw new Error('Contrived Error')
}

it('wins() returns Winner', async () => {
  expect(await wins()).to.equal('Winner')
})

it('fails() throws Error', async () => {
  await expect(fails()).to.be.rejectedWith(Error)
})

We add the chai-as-promised plugin with

chai.use(require('chai-as-promised'))

Then we test the wins and fails async functions by calling it with an async function.

And we get the resolved value of wins with await and use equal to check it resolve value.

And we test for rejected promise from the fails function by call fails and then use rejectedWith with awit to check the error thrown.

Conclusion

To verify that an exception is thrown using Mocha and Chai and async and await, we can use the chai-as-promised package.

Categories
JavaScript Answers

How to time out a promise if failed to complete in time with Node.js?

Sometimes, we want to time out a promise if failed to complete in time with Node.js.

In this article, we’ll look at how to time out a promise if failed to complete in time with Node.js.

How to time out a promise if failed to complete in time with Node.js?

To time out a promise if failed to complete in time with Node.js, we can use the Promise.race method.

For instance, we write

const withTimeout = (millis, promise) => {
  const timeout = new Promise((resolve, reject) =>
    setTimeout(
      () => reject(`Timed out after ${millis} ms.`),
      millis));
  return Promise.race([
    promise,
    timeout
  ]);
}

to define the withTimeout function that calls Promise.race with the promise and the timeout promise.

Promise.race returns the promise that’s settled the earliest so if timeout is settled before promise, it’ll be returned.

Then we can use withTimeout in an async function by writing

await withTimeout(5000, doSomethingAsync());

where doSomethingAsync is an async function.

Conclusion

To time out a promise if failed to complete in time with Node.js, we can use the Promise.race method.