Categories
JavaScript Answers

How to fix Node.js socket.io.js not found?

To fix Node.js socket.io.js not found, we expose the folder with socket.io.js as the static folder.

For instance, we write

app.use(express.static(path.join(__dirname, "/")));

to call express.static to expose the root folder as the static folder.

And then we can put socket.io.js there and use it in a script tag like

<script src="//socket.io.js"></script>
Categories
JavaScript Answers

How to map over an object and change one properties value using JavaScript?

To map over an object and change one properties value using JavaScript, we use the spread operator.

For instance, we write

const original = { a: 1, b: 2 };
const copy = { ...original, c: 3 };

to spread the properties of the original object into the copy object.

And we add the c property to copy to set ites c property to 3.

Categories
JavaScript Answers

How to fix not being able to get CSS file with Node Express?

To fix not being able to get CSS file with Node Express, we expose the folder with the CSS file as a static folder.

Then we write

app.use(express.static(path.join(__dirname, "public")));

to call express.static with the path to expose as the static folder.

Therefore, when we put our CSS file in the public folder, we can get it by using the file name as the URL.

Categories
JavaScript Answers

How to set cell width when export .xlsx files with Node js-xlsx?

To set cell width when export .xlsx files with Node js-xlsx, we set the wch property.

For instance, we write

const fitToColumn = (arrayOfArray) => {
  return arrayOfArray[0].map((a, i) => ({
    wch: Math.max(
      ...arrayOfArray.map((a2) => (a2[i] ? a2[i].toString().length : 0))
    ),
  }));
};

const worksheet = XLSX.utils.aoa_to_sheet(arrayOfArray);
worksheet["!cols"] = fitToColumn(arrayOfArray);

to define the fitToColumn function that returns an array with objects with the wch property that has the width value.

We set the width to the max number of characters in the cell of each column.

We get the worksheet from the aoa_to_sheet called with our arrayOfArray nested array of data.

Categories
JavaScript Answers

How to create folder or key on s3 using AWS SDK for Node.js?

To create folder or key on s3 using AWS SDK for Node.js, we call the upload method.

For instance, we write

const AWS = require("aws-sdk");
AWS.config.region = "us-east-1";
const s3Client = new AWS.S3();

const params = {
  Bucket: "your_bucket_goes_here",
  Key: "folderInBucket/",
  ACL: "public-read",
  Body: "body does not matter",
};

s3Client.upload(params, (err, data) => {
  if (err) {
    console.log("Error creating the folder: ", err);
  } else {
    console.log("Successfully created a folder on S3");
  }
});

to call upload with the params object that has the Bucket and Key of the file.

And Body has the body of the file we’re uploading.

We get the uploaded data from data and errors from err in the callback.