Categories
JavaScript Answers

How to get folder path from a file with Node.js?

To get folder path from a file with Node.js, we call the path.dirname method.

For instance, we write

const path = require("path");
const dir = path.dirname("G:\\node-demos\\7-node-module\\demo\\config.json");

to call path.dirname to return the folder path for the "G:\\node-demos\\7-node-module\\demo\\config.json" path.

Categories
JavaScript Answers

How to use Sequelize findAll with sort order in Node.js?

To use Sequelize findAll with sort order in Node.js, we call findAll with an object with the order property.

For instance, we write

const companies = Company.findAll({
  where: {
    id: [46128, 2865, 49569, 1488, 45600, 61991, 1418, 61919, 53326, 61680],
  },
  order: [
    ["id", "DESC"],
    ["name", "ASC"],
  ],
  attributes: ["id", "logo_version", "logo_content_type", "name", "updated_at"],
});

to call findAll with an object with the order property to return the results sorted by id descending and by name ascending.

Categories
JavaScript Answers

How to get response from S3 getObject in Node.js?

To get response from S3 getObject in Node.js, we call the getObject method.

For instance, we write

const AWS = require("aws-sdk");

const s3 = new AWS.S3();

const getObject = async (bucket, objectKey) => {
  try {
    const params = {
      Bucket: bucket,
      Key: objectKey,
    };

    const data = await s3.getObject(params).promise();

    return data.Body.toString("utf-8");
  } catch (e) {
    throw new Error(`Could not retrieve file from S3: ${e.message}`);
  }
};

const myObject = await getObject("my-bucket", "path/to/the/object.txt");

to define the getObject function.

In it we call getObject with the params object that has the Bucket and Key into to get the object.

We call promise to return a promise with the object data.

Then we convert it to a string with data.Body.toString`.

Categories
JavaScript Answers

How to make multiple projects share node_modules directory with JavaScript?

To make multiple projects share node_modules directory with JavaScript, we use pnpm.

To install it globally, we run

npm install -g pnpm

Then we install all the packages for all the projects in the folder in one node_modules directory with

pnpm recursive install
Categories
JavaScript Answers

How to fix Sinon error Attempted to wrap function which is already wrapped with JavaScript?

To fix Sinon error Attempted to wrap function which is already wrapped with JavaScript, we should restore our stubs after the test is done.

For instance, we write

beforeEach(() => {
  sandbox = sinon.createSandbox();
  mockObj = sandbox.stub(testApp, "getObj", fakeFunction);

});

afterEach(() => {
  sandbox.restore();
});

to call createSandvox to create the sandbox.

Then we call sandvbox.stub to create a stub in the beforeEach callback, which runs before each test.

Then in the afterEach callback, we call sandbox.restore to restore the stubs after each test.