简体   繁体   中英

module.exports a function in nodejs

I want to export function and variable from one file ( module ) to another . This is how it is

    // animals.js 
        function weight () {
         return "90kgs"; 
    }
    module.exports = weight();

    // tiger.js 
    var animal = require('./animals.js');
    module.exports = { 
             'animalWeight' : function animal.weight(),
             'stripes' : true 
    }


   // zoo.js
   var tiger = require('./tiger.js');
   tiger.animalWeight(); // should return 90kgs
   tiger.stripes ; // should return true

How to achieve above. I get following error

   'animalWeight' : function animal.weight(),
                                   ^
    SyntaxError: Unexpected token .

When you export a function, you'd reference it

function weight () {
     return "90kgs"; 
}
module.exports = weight;

now when you import it, you get that function, and can reference it again

var animal = require('./animals.js');

module.exports = { 
    'animalWeight' : animal,
    'stripes' : true 
}

and when you import that again, you can call that function

var tiger = require('./tiger.js');

tiger.animalWeight(); // "90kgs"
tiger.stripes ; // true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM