Categories
JavaScript Answers

How to make synchronous requests in Node.js?

Sometimes, we want to make synchronous requests in Node.js.

In this article, we’ll look at how to make synchronous requests in Node.js.

How to make synchronous requests in Node.js?

To make synchronous requests in Node.js, we can use the sync-request module.

To install it, we run

npm i sync-request

Then we use it by writing

const request = require('sync-request')

try {
  const res1 = request('GET', url1);
  const res2 = request('GET', url2);
} catch (e) {}

to call request with 'GET' to make GET requests to url1 and url2.

Conclusion

To make synchronous requests in Node.js, we can use the sync-request module.

Categories
JavaScript Answers

How to check in Node if module exists and if exists to load?

Sometimes, we want to check in Node if module exists and if exists to load.

In this article, we’ll look at how to check in Node if module exists and if exists to load.

How to check in Node if module exists and if exists to load?

To check in Node if module exists and if exists to load, we can wrap our require call with a try-catch block.

For instance, we write

try {
  const m = require('/foo/bar');
  //  ...
} catch (ex) {
  handleErr(ex);
}

to wrap our require call with a try block.

If the module doesn’t exist, then an error will be thrown, and so we can catch the error with the catch block.

Conclusion

To check in Node if module exists and if exists to load, we can wrap our require call with a try-catch block.

Categories
JavaScript Answers

How to log the response body with Express?

Sometimes, we want to log the response body with Express.

In this article, we’ll look at how to log the response body with Express.

How to log the response body with Express?

To log the response body with Express, we can create our own middleware to intercept the response and log it.

For instance, we write

const logResponseBody = (req, res, next) => {
  const oldWrite = res.write
  const oldEnd = res.end;

  const chunks = [];

  res.write = (chunk, ...args) => {
    chunks.push(chunk);
    return oldWrite.apply(res, [chunk, ...args]);
  };

  res.end = (chunk, ...args) => {
    if (chunk) {
      chunks.push(chunk);
    }
    const body = Buffer.concat(chunks).toString('utf8');
    console.log(req.path, body);
    return oldEnd.apply(res, [chunk, ...args]);
  };

  next();
}

app.use(logResponseBody);

to create the logResponseBody middleware function that sets res.write to a function that calls chunks.push to push the response chunks to the chunks array.

And then we return the result of the original res.write write method, which is stored in oldWrite.

Likewise, we set res.end to a method that combine the chunks into a buffer with Buffer.concat.

And then we log the body with console.log.

And then we call oldEnd.apply and return the results.

Finally, we call next to call the next middleware.

Conclusion

To log the response body with Express, we can create our own middleware to intercept the response and log it.

Categories
JavaScript Answers

How to add error handling with Express Passport in Node.js?

Sometimes, we want to add error handling with Express Passport in Node.js.

In this article, we’ll look at how to add error handling with Express Passport in Node.js.

How to add error handling with Express Passport in Node.js?

To add error handling with Express Passport in Node.js, we can set the failureRedirect and failureFlash options.

For instance, we write

app.post('/login', passport.authenticate('local', {
  successRedirect: '/loggedin',
  failureRedirect: '/login',
  failureFlash: true
}));

to set failureRedirect to '/login' to redirect to the /login route when login failed.

When failureFlash is set to true, we can store the message we call next with if the connect-flash middleware is installed.

Conclusion

To add error handling with Express Passport in Node.js, we can set the failureRedirect and failureFlash options.

Categories
JavaScript Answers

How to use populate and aggregate in same statement with MongoDB and Node.js?

Sometimes, we want to use populate and aggregate in same statement with MongoDB and Node.js.

In this article, we’ll look at how to use populate and aggregate in same statement with MongoDB and Node.js.

How to use populate and aggregate in same statement with MongoDB and Node.js?

To use populate and aggregate in same statement with MongoDB and Node.js, we can call populate with the aggregation result returned from aggergate.

For instance, we write

const pop = async () => {
  const appointments = await Appointments.aggregate([
    //...
  ]);
  await Patients.populate(appointments, {
    path: "patient"
  });
  return appointments;
}

to call aggregate to return a promise with the aggregation result.

Then we call populate with the appointments aggregation to populate the aggregation result with the 'patient' field.

And then we return the appointments result with the populate results.

Conclusion

To use populate and aggregate in same statement with MongoDB and Node.js, we can call populate with the aggregation result returned from aggergate.