Home > Net >  How do you export an object in a module in nodejs?
How do you export an object in a module in nodejs?

Time:10-09

There is something wrong with the way I understand how to use classes in a Javascript module and export them, or some bad assumption I made about how nodejs works. Please help me understand this better. I wanted to write a module that exposed an object that will "store things safely." I have a file ("safestore.js") with this in it:

class Safestore {
    constructor() {
    console.log("SUCCESS!");
        }
    ... // I defined other methods here...
}
exports.safestore = Safestore; // I tried this with `new Safestore` and `new Safestore()` too.

I run nodejs on my command line and then:

> ss = require('./safestore');
{ safestore: [Function] }
> s = ss.safestore('pwd','./encFile.enc');
ReferenceError: Safestore is not defined...

Why is it telling me that Safestore is not defined while executing the safestore function which is defined in the same file where Safestore is, actually defined?

CodePudding user response:

ss.safestore is a class constructor therefore it must be invoked with the new operator

ss = require('./safestore');
s = new ss.safestore('pwd','./encFile.enc');

Why is it telling me that Safestore is not defined while executing code

I don't get that error running your code with Node v17.4.0

CodePudding user response:

The question does not contain enough information, although there is a clue. node and nodejs are two different pieces of software, and I was using the wrong one. I also didn't specify what version of nodejs I ran from my command line. When I ran it with node (instead of nodejs) I got errors that made sense and I was able to fix them.

Thanks to @Ethicist for listing the version of Node he used, as this got me to double check all those things.

I just need to remember that node and nodejs each do different things. Further research shows me that nodejs is a symlink to version 8.10.0 of node.js, and node is a symlink to the version that I set with nvm. I solved the problem permanently for myself with sudo rm /user/bin/nodejs and I'll remember, if I ever see an error that says nodejs doesn't exist, that it wants the old version of node.js.

  • Related