Categories
JavaScript Answers

How to add a debug script to Node NPM?

To add a debug script to Node NPM, we run node with the --inspect option.

For instance, we write

{
  "scripts": {
    "debug": "node --inspect server.js"
  }
}

to add the debug script into our package.json file.

We make it run node with the --inspect option to let us debug server.js.

Then we run it with

npm run debug
Categories
JavaScript Answers

How to check if ID exists in a collection with Node Mongoose?

To check if ID exists in a collection with Node Mongoose, we call the countDocument method.

For instance, we write

User.countDocuments({ _id: userID }, (err, count) => {
  if (count > 0) {
    //...;
  }
});

to call countDocuments with an object with _id set to the value we’re looking for.

The count parameter in the callback has the number of items with the _id value.

Categories
JavaScript Answers

How to send no cache headers in Node.js server?

To send no cache headers in Node.js server, we call the writeHead method.

For instance, we write

res.writeHead(200, {
  "Content-Type": mimeType,
  "Content-Length": contents.length,
  "Accept-Ranges": "bytes",
  "Cache-Control": "no-cache",
});

to call writHeader with an object with the response headers and values.

We return the Content-Type, Content-Length, Accept-Ranges, and Cache-Control headers.

We set Cache-Control to no-cache to disable cache.

Categories
JavaScript Answers

How to copy/move all objects in Amazon S3 from one prefix to other using the AWS SDK for Node.js?

To copy/move all objects in Amazon S3 from one prefix to other using the AWS SDK for Node.js, we use the coptObject method.

For instance, we write

const AWS = require("aws-sdk");
AWS.config.update({
  credentials: new AWS.Credentials("..."),
});
AWS.config.setPromisesDependency(require("bluebird"));
const s3 = new AWS.S3();

const bucketName = "bucketName";
const folderToMove = "folderToMove/";
const destinationFolder = "destinationFolder/";
try {
  const listObjectsResponse = await s3
    .listObjects({
      Bucket: bucketName,
      Prefix: folderToMove,
      Delimiter: "/",
    })
    .promise();

  const folderContentInfo = listObjectsResponse.Contents;
  const folderPrefix = listObjectsResponse.Prefix;

  await Promise.all(
    folderContentInfo.map(async (fileInfo) => {
      await s3
        .copyObject({
          Bucket: bucketName,
          CopySource: `${bucketName}/${fileInfo.Key}`,
          Key: `${destinationFolder}/${fileInfo.Key.replace(folderPrefix, "")}`,
        })
        .promise();

      await s3
        .deleteObject({
          Bucket: bucketName,
          Key: fileInfo.Key,
        })
        .promise();
    })
  );
} catch (err) {
  console.error(err);
}

to call folderContentInfo.map with a callback to return an array of promises that we get from copyObject.

We call copyObject with an object with the Bucket, the CopySource source path, and the Key to copy to.

Then we call delete object with an object with the Bucket and Key to delete the old object.

We call Promise.all with the array to run all the copy and delete operations.

Categories
JavaScript Answers

How to route all requests to index.html with Node Express?

To route all requests to index.html with Node Express, we call the sendFile method.

For instance, we write

const express = require("express");
const server = express();

server.use("/public", express.static(__dirname + "/static-files-dir"));

server.get("/some-route", (req, res) => {
  res.send("ok");
});

server.get("/*", (req, res) => {
  res.sendFile(__dirname + "/index.html");
});

const port = 8000;
server.listen(port, () => {
  console.log("server listening on port " + port);
});

to create a catch route by calling server.get with '.*'.

And then we call sendFile with the path of index.html to render that as the response.