Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs: 'require' a module in Nodejs doesn't work with certain filename

Long-time user, first time asking a question.

I have a file (let's call it file.js) in which I'm attempting to require another file called user.service.js at the top of the file:

var userService = require('./user.service');

I'm quite sure that the path is correct and that the user.service.js file is exporting a populated object:

In user.service.js:

module.exports = {
    signIn: signIn,
    signUp: signUp,
    updateProfile: updateProfile
};

However, userService is always an empty object {}. The odd thing is, if I recreate the file with another name in the same directory (e.g. user.service2.js), the require statement works properly. Or, if I rename file.js to something else, e.g. file2.js, the call works. Additionally, if I require the file inside a function within user.service.js, the statement works as well. However, I'd prefer to have the require statement at the top of the file and available to all functions inside it.

Thanks in advance for the help.

Edit:

Here's some sample code:

var userService = require('./user.service');

var testFunc = function () {
    console.log(userService);
    // this logs: {}

    var userServiceInternal = require('./user.service');
    console.log(userServiceInternal);
    // This logs: 
    // {
    //     signIn: [Function],
    //     signUp: [Function],
    //     updateProfile: [Function]
    // }
};
like image 522
Jack12358 Avatar asked Nov 01 '22 02:11

Jack12358


1 Answers

I figured it out...I had a circular dependency. Thanks for the comments!

like image 93
Jack12358 Avatar answered Nov 15 '22 04:11

Jack12358