Categories
JavaScript Answers

How to add simple file upload to S3 using aws-sdk and Node/Express?

To add simple file upload to S3 using aws-sdk and Node/Express, we use the multer-s3 package.

For instance, we write

const express = require("express"),
  bodyParser = require("body-parser"),
  multer = require("multer"),
  s3 = require("multer-s3");

const app = express();

app.use(bodyParser.json());

const upload = multer({
  storage: s3({
    dirname: "/",
    bucket: "bucket-name",
    secretAccessKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    accessKeyId: "XXXXXXXXXXXXXXX",
    region: "us-east-1",
    filename: (req, file, cb) => {
      cb(null, file.originalname);
    },
  }),
});

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

app.post("/upload", upload.array("upl"), (req, res, next) => {
  res.send("Uploaded!");
});

app.listen(3000, () => {
  console.log("Example app listening on port 3000!");
});

to call multer with an object that has storage set to the storage object created by s3.

We call s3 with an object with the AWS credentials, the region and the filename method to set the file name.

bucket has the bucket name. dirname is the upload file folder.

We call upload.array with the key name of the form data entry with the files to return the middleware to let us accept upload files.

Categories
JavaScript Answers

How to fix Please run npm cache clean error with Node?

To fix Please run npm cache clean error with Node, we run npm cache clean.

To do this, we run

npm cache clean --force

to clear the npm cache by force.

Categories
JavaScript Answers

How to fix Karma/Jasmine times out without running tests with Node?

To fix Karma/Jasmine times out without running tests with Node, we increase the timeout for running tests.

For instance, in karma.conf.js, we write

module.exports = function (config) {
  config.set({
    //...
    captureTimeout: 60000,
    browserDisconnectTimeout: 10000,
    browserDisconnectTolerance: 1,
    browserNoActivityTimeout: 60000,
  });
};

to set browserNoActivityTimeout to 60000ms to increase the test timeout.

Categories
JavaScript Answers

How to split and modify a string in Node?

To split and modify a string in Node, we call the split and map methods.

For instance, we write

const str = "123, 124, 234,252";
const arr = str.split(",").map((val) => Number(val) + 1);
console.log(arr);

to call split to split the str string by the commas into a string array.

And then we call map to map each value to their new value by converting them to a number and add 1 to it.

Categories
JavaScript Answers

How to buffer entire file in memory with Node.js?

To buffer entire file in memory with Node.js, we call readFile.

For instance, we write

const fs = require("fs");

fs.readFile("/etc/passwd", (err, data) => {
  // ...
});

to call readFile to open the /etc/passwd file.

And we get the open file data from data.