Categories
JavaScript Answers

How to set an environmental variable in Node.js?

Sometimes, we want to set an environmental variable in Node.js.

In this article, we’ll look at how to set an environmental variable in Node.js.

How to set an environmental variable in Node.js?

To set an environmental variable in Node.js, we can set it as a property of the process.env property.

For instance, we write

process.env['VARIABLE'] = 'value';

or

process.env.VARIABLE = 'value';

to set the VARIABLE environment variable to 'value'.

Conclusion

To set an environmental variable in Node.js, we can set it as a property of the process.env property.

Categories
JavaScript Answers

How to get the _id of inserted document in Mongo database in Node.js?

Sometimes, we want to get the _id of inserted document in Mongo database in Node.js.

In this article, we’ll look at how to get the _id of inserted document in Mongo database in Node.js.

How to get the _id of inserted document in Mongo database in Node.js?

To get the _id of inserted document in Mongo database in Node.js, we can get it from the callback of the collection insert method.

For instance, we write

collection.insert(objectToInsert, (err) => {
  if (err) {
    return;
  }
  const objectId = objectToInsert._id;
});

to call collection.insert with objectToInsert to insert the object as a document in collection.

to get the _id of the insert document from the objectToInsert._id property.

It should be available in the callback since the callback runs after the document is inserted.

Conclusion

To get the _id of inserted document in Mongo database in Node.js, we can get it from the callback of the collection insert method.

Categories
JavaScript Answers

How to load vanilla JavaScript libraries into Node.js?

Sometimes, we want to load vanilla JavaScript libraries into Node.js.

in this article, we’ll look at how to load vanilla JavaScript libraries into Node.js.

How to load vanilla JavaScript libraries into Node.js?

To load vanilla JavaScript libraries into Node.js, we can use readFileSync to read the JavaScript file.

Then we call the runInNewContext method from the vm module to run the script in a new context.

For instance, we write

execfile.js

const vm = require("vm");
const fs = require("fs");

module.exports = (path, context = {}) => {
  const data = fs.readFileSync(path);
  vm.runInNewContext(data, context, path);
  return context;
}

to create the execfile.js module, which exports a function that calls readFileSync with the script path.

Then we call vm.runInNextContext with the data, context, and path to run the script in the given context.

And then we return the context.

Then we require execfile.js in another module and call the exported function with

app.js

const execfile = require("./execfile");
const context = execfile("example.js", {
  someGlobal: 42
});
context.getSomeGlobal()

We call execfile with the 'example.js' and a context object that incorporate into the returned context.

And then we call context.getSomeGlobalto run the global function in theexample.js` script.

Conclusion

To load vanilla JavaScript libraries into Node.js, we can use readFileSync to read the JavaScript file.

Then we call the runInNewContext method from the vm module to run the script in a new context.

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.