Categories
JavaScript Answers

How to find the size of the file in Node.js?

To find the size of the file in Node.js, we use the statSync method.

For instance, we write

const fs = require("fs");

const stats = fs.statSync("myfile.txt");
const fileSizeInBytes = stats.size;
const fileSizeInMegabytes = fileSizeInBytes / (1024 * 1024);

to call statSync to get the stats for the myfile.txt file.

We get the file size in bytes with stats.size.

Then we convert it to megabytes by dividing it by 1024 * 1024.

Categories
JavaScript Answers

How to select where in array of _id with MongoDB and JavaScript?

To select where in array of _id with MongoDB and JavaScript, we call the find method.

For instance, we write

db.collection.find({ _id: { $in: [ObjectId("1"), ObjectId("2")] } });

to call find with an object with the _id property set to an array with the object IDs to look for in the collection.

Categories
JavaScript Answers

How to add a timestamp field with Mongoose and JavaScript?

To add a timestamp field with Mongoose and JavaScript, we set the timestamps option to true.

For instance, we write

const mySchema = new mongoose.Schema({ name: String }, { timestamps: true });

to create a schema with the name string field.

We set timestamps to true to make it a timestamp field.

Categories
JavaScript Answers

How to fix Permission denied when installing npm modules in OSX?

To fix Permission denied when installing npm modules in OSX, we change the permission of the node_modules directory.

For instance, we run

sudo chown -R $(whoami) $(npm config get prefix)/{lib/node_modules,bin,share}

to run chown to get the user with whoami and then set the node_modules, bin, and share directories’ owner to the current user.

And then we install packages with

sudo npm install
Categories
JavaScript Answers

How to auto generate migrations with Node.js Sequelize CLI from Sequelize models?

To auto generate migrations with Node.js Sequelize CLI from Sequelize models, we run sequelize model:create.

For instance, we run

sequelize model:create --name MyUser --attributes first_name:string,last_name:string,bio:text

to create the MyUser model with the first_name, last_name, and bio fields.

Then a migration file will be created along with the model file.