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.

Categories
JavaScript Answers

How to convert a directory structure in the filesystem to JSON with Node.js?

Sometimes, we want to convert a directory structure in the filesystem to JSON with Node.js.

In this article, we’ll look at how to convert a directory structure in the filesystem to JSON with Node.js.

How to convert a directory structure in the filesystem to JSON with Node.js?

To convert a directory structure in the filesystem to JSON with Node.js, we can loop through the files and directories recursively.

For instance, we write

const fs = require('fs')
const path = require('path')

const dirTree = (filename) => {
  const stats = fs.lstatSync(filename)
  const info = {
    path: filename,
    name: path.basename(filename)
  };

  if (stats.isDirectory()) {
    info.type = "folder";
    info.children = fs.readdirSync(filename).map((child) => {
      return dirTree(`${filename}/${child}`);
    });
  } else {
    info.type = "file";
  }
  return info;
}

to define the dirTree function that gets the items in a directory with lstatSync.

Then we check if filename is a directory with stats.isDirectory.

If it is, then we call readdirSync to read the folder and call map with a callback that calls dirTree to read the directory.

Otherwise, we set info.type to 'file'.

And finally, we return info when we’re done.

Conclusion

To convert a directory structure in the filesystem to JSON with Node.js, we can loop through the files and directories recursively.