Categories
JavaScript Answers

How to get path from the request with Node.js?

To get path from the request with Node.js, we get the URL from the req object.

For instance, we write

const api = express.Router();

api.use((req, res, next) => {
  const fullUrl = req.protocol + "://" + req.get("host") + req.originalUrl;
  next();
});

app.use("/", api);

to get the request URL’s protocol with req.protocol

We get the request URL’s host name with req.get("host").

And we get the rest of the request URL with req.originalUrl.

Categories
JavaScript Answers

How to use sprintf with Node.js?

To use sprintf with Node.js, we use the util.format method.

For instance, we write

const s = util.format("hello %s", "world");

to call util.format to return a formatted string with %s filled in with the arguments after the first.

Therefore, s is 'hello world'.

Categories
JavaScript Answers

How to get the string length in bytes in Node?

To get the string length in bytes in Node, we call the Buffer.byteLength method.

For instance, we write

const getBytes = (string) => {
  return Buffer.byteLength(string, "utf8");
};

to call Buffer.byteLength with the string to get the string‘s length in byte.

Categories
JavaScript Answers

How to fix MongoNetworkError: failed to connect to server [localhost:27017] on first connect with Node MongoDB?

To fix MongoNetworkError: failed to connect to server [localhost:27017] on first connect with Node MongoDB, we should make sure we’re connecting to a reachable Mongo server.

For instance, we write

await mongoose.connect("mongodb://localhost/testdb");

to call mongoose.connect to connect to the testdb database on localhost.

The error shouldn’t be thrown if it’s reachable.

Categories
JavaScript Answers

How to Add, Delete new Columns in Node Sequelize CLI?

To Add, Delete new Columns in Node Sequelize CLI, we create a migration file.

For instance, we run

$ sequelize migration:create --name name_of_your_migration

to create a migration.

Then we write

module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.addColumn("Todo", "completed", Sequelize.BOOLEAN);
  },

  down: (queryInterface, Sequelize) => {
    return queryInterface.removeColumn("Todo", "completed");
  },
};

to call addColumn to add a column with the table name, column name, and data type.

We call removeColumn with the table name and column name to remove it.

Then we run

$ sequelize db:migrate

to call the up function in the migration file.