Module.exports in an if/else statement

I’m writing some encryption functions in NodeJS. The functions work like createCipheriv(encryptionType, text, key, iv ). The key needs to be 32 characters long, and the IV needs to be 16 characters long. So, I want to do something like:

if (process.env.IV.length() === 16 || process.env.key.length() === 32) {
module.exports = encryptionFunctions
} else {
module.exports = undefined;
console.error("IV or key lengths are incorrect") 
}

Is this possible?

This should work, as module.exports = is just a setter function, so it should act the same as any other function. In theory.

1 Like

Hm ok - I’ll try this on a random project later on today. Thanks!

You should rather throw an error if some of the details are incorrect:

if (
  process.env.IV.length !== 16 ||
  process.env.key.length !== 32
) throw new Error("IV or key lengths are invalid!");

module.exports = encryptionFunctions;

Oh, I’ve seen the new Error() syntax before - does it to anything special or different from console.error?

The error object has been around since the beginning of javascript. All it does is simply storing an error message and collecting the stack trace of where the error appeared from. However throw simply takes any object or value and calls .toString() and outputs it to stderr.

In a node process the console has two different output streams, stdout and stderr, every console method uses stdout except console.error which uses stderr. The point of having two different output streams is to separate error logs and debug/access/etc logs

The day I stared learning NodeJS, I didn’t understand stdin, stdout or stderr.
One year later, I still don’t…

Thanks for explaining!