Categories
JavaScript Answers

How to read file from aws s3 bucket using Node fs?

To read file from aws s3 bucket using Node fs, we create a write stream.

For instance, we write

const s3 = new AWS.S3({ apiVersion: "2006-03-01" });
const params = { Bucket: "myBucket", Key: "myImageFile.jpg" };
const file = require("fs").createWriteStream("/path/to/file.jpg");
s3.getObject(params).createReadStream().pipe(file);

to call createWriteStreamn with the path to write the data to.

Then we call getObject to get the object by the bucket and key.

And we call createReadStream to read the file and call pipe to pipe the file to the file write stream to write it.

Categories
JavaScript Answers

How to use global variable in Node.js?

To use global variable in Node.js, we create a module.

For instance, we write

module.exports = new Logger(customConfig);

in logger.js to export the Logger object.

Then we write

const logger = require("./logger");
logger.log("foo");

in app.js to call require to import the logger.js module and call logger.

Categories
JavaScript Answers

How to clone an object with Node.js?

To clone an object with Node.js, we use the Lodash clone method.

For instance, we write

const _ = require("lodash");

const objects = [{ a: 1 }, { b: 2 }];
const cloned = _.clone(objects);

to call clone to clone the objects array and return the clone.

Categories
JavaScript Answers

How to make Sequelize table without column ‘id’ with Node.js?

To make Sequelize table without column ‘id’ with Node.js, we call the removeAttribute method.

For instance, we write

AcademyModule = sequelize.define(
  "academy_module",
  {
    academy_id: DataTypes.INTEGER,
    module_id: DataTypes.INTEGER,
    module_module_type_id: DataTypes.INTEGER,
    sort_number: DataTypes.INTEGER,
    requirements_id: DataTypes.INTEGER,
  },
  {
    freezeTableName: true,
  }
);
AcademyModule.removeAttribute("id");

to define the AcademyModule model with define.

We map it to the academy_module table in the database.

We call removeAttribute to remove the id column.

Categories
JavaScript Answers

How to import node’s path module using import path from ‘path’ with Node.js?

To import node’s path module using import path from ‘path’ with Node.js, we add the type definitions for node.

And the we import the module.

To install the type definitions, we run

npm install --save-dev @types/node

Then we import path with

import * as path from 'path';

to import all members into the path object.