Categories
JavaScript Answers

How to redirect to previous page after authentication in Node.js using Passport.js?

Sometimes, we want to redirect to previous page after authentication in Node.js using Passport.js.

In this article, we’ll look at how to redirect to previous page after authentication in Node.js using Passport.js.

How to redirect to previous page after authentication in Node.js using Passport.js?

To redirect to previous page after authentication in Node.js using Passport.js, we can use our own middleware to do the redirect depending on authentication status.

For instance, we write

const restrict = (req, res, next) => {
  if (!req.session.userId) {
    req.session.redirectTo = '/account';
    res.redirect('/login');
  } else {
    next();
  }
};

app.get('/auth/return', restrict, (req, res) => {
  const redirectTo = req.session.redirectTo || '/';
  delete req.session.redirectTo;
  res.redirect(redirectTo);
});

to define the restrict middleware function that checks if req.session.userId is defined.

If it is, then the user is authenticated and we call next to call the next middleware which does the redirect.

Otherwise, we set req.session.redirectTo to '/account' and call res.redirect to redirect the user to '/login'.

In the /auth/return route handler middleware, we remove the req.session.redirectTo property with delete.

And then we do the redirect with res.redirect to the redirectTo path.

Conclusion

To redirect to previous page after authentication in Node.js using Passport.js, we can use our own middleware to do the redirect depending on authentication status.

Categories
JavaScript Answers

How to read all files in a directory, store them in objects, and send the object with Node.js?

Sometimes, we want to read all files in a directory, store them in objects, and send the object with Node.js.

In this article, we’ll look at how to read all files in a directory, store them in objects, and send the object with Node.js.

How to read all files in a directory, store them in objects, and send the object with Node.js?

To read all files in a directory, store them in objects, and send the object with Node.js, we can use the promise versions of the fs module methods.

For instance, we write

const fs = require('fs');
const util = require('util');

const readdir = util.promisify(fs.readdir);
const readFile = util.promisify(fs.readFile);

const readFiles = async dirname => {
  try {
    const filenames = await readdir(dirname);
    console.log({
      filenames
    });
    const filesPromise = filenames.map(filename => {
      return readFile(dirname + filename, 'utf-8');
    });
    const response = await Promise.all(filesPromise);
    return filenames.reduce((acc, filename, currentIndex) => {
      const content = response[currentIndex];
      return {
        ...acc,
        [filename]: content
      };
    }, {});
  } catch (error) {
    console.error(error);
  }
};

to define the readFiles function.

In it, we call readdir with the dirname folder path to get the file paths in the folder.

Then we call filenames.map to map each filename to a promise that resolves to the file content by calling readFile.

Then we call Promise.all with filesPromise to return a promise which resolves to an array of all the file contents.

And then we call filenames.reduce get the file content from response[currentIndex] and return an object with the filename as the property name and content as their values.

The fs methods are converted to functions that returns promises with

const readdir = util.promisify(fs.readdir);
const readFile = util.promisify(fs.readFile);

Conclusion

To read all files in a directory, store them in objects, and send the object with Node.js, we can use the promise versions of the fs module methods.

Categories
JavaScript Answers

How to wait some asynchronous tasks complete in Node.js?

Sometimes, we want to wait some asynchronous tasks complete in Node.js.

In this article, we’ll look at how to wait some asynchronous tasks complete in Node.js.

How to wait some asynchronous tasks complete in Node.js?

To wait some asynchronous tasks complete in Node.js, we can use promises.

For instance, we write

const mongoose = require('mongoose');

mongoose.connect('...');
const conn = mongoose.connection;

const promises = ['aaa', 'bbb', 'ccc'].map((name) => {
  return new Promise((resolve, reject) => {
    const collection = conn.collection(name);
    collection.drop((err) => {
      if (err) {
        return reject(err);
      }
      console.log('dropped ' + name);
      resolve();
    });
  });
});

(async () => {
  await Promise.all(promises)
  // ...
})()

to call map on an array with a callback to map the array entries to promises.

We create the promise with the Promise constructor.

We call Promise with a callback that calls resolve when the async operation is done.

And then we call Promise.all with the array of promises to run all the promises.

await will make sure all the promises are done until the lines below it is run.

Conclusion

To wait some asynchronous tasks complete in Node.js, we can use promises.

Categories
JavaScript Answers

How to add timestamps to all console messages with Express and Node.js?

Sometimes, we want to add timestamps to all console messages with Express and Node.js.

In this article, we’ll look at how to add timestamps to all console messages with Express and Node.js.

How to add timestamps to all console messages with Express and Node.js?

To add timestamps to all console messages with Express and Node.js, we can customize the Express logger with express.logger.format.

For instance, we write

const df = require('console-stamp/node_modules/dateformat');

express.logger.format('mydate', () => {
  return df(new Date(), 'HH:MM:ss.l');
});

app.use(express.logger('[:mydate] :method :url :status :res[content-length] - :remote-addr - :response-time ms'));

to require the console-stamp module.

We install it by running

npm i console-stamp

Then we call express.logger.format with the name of the logger and a function to returns the logger formatter object by calling df to include the date in the log entries.

Then we call express.logger to return the logging middleware with the custom format.

And we call app.use to use the logger middleware.

Conclusion

To add timestamps to all console messages with Express and Node.js, we can customize the Express logger with express.logger.format.

Categories
JavaScript Answers

How to pass an app instance to routes from a different file with Express?

Sometimes, we want to pass an app instance to routes from a different file with Express.

In this article, we’ll look at how to pass an app instance to routes from a different file with Express.

How to pass an app instance to routes from a different file with Express?

To pass an app instance to routes from a different file with Express, we can call require on the module with the routes in the module that we defined the app instance in.

For instance, we write

app.js

const app = module.exports = express();
app.use(app.router);

require('./routes');

to export the app instance created by express.

Then in routes/index.js, we write

const app = require('../app');

app.get('/', (req, res, next) => {
  res.render('index');
});

require('./user');
require('./blog');

to require app.js and then call app.get to add a GET route.

We also call require with other route modules which require app individually themselves to add the routes from those files.

Conclusion

To pass an app instance to routes from a different file with Express, we can call require on the module with the routes in the module that we defined the app instance in.