Node js module exports variable undefined

Node js module exports variable undefined
0

#1

i am new to node.js. I was working with module.exports and have certain doubt . I have two files

//test.js
module.exports.lm="abc";
module.exports = "hello";

//index.js
var p = require('./test.js');
var l = require('./test.js').lm;
console.log(p); //hello
console.log(l); //undefined

Can someone explain why this is happening.


#2

module.exports.lm=“abc”;

exports has a property named lm with a value “abc”

Then you set exports to “hello”;
exports is now set to a value of "hello"
No more lm property.

do this instead:

module.exports = {
lm: “abc”,
hello: “hello”
}

then you can do this:

// destructuring assignment
var {lm, hello} = require(’./test.js’);

or

var lm = require(’./test.js’).lm;
var hello = require(’./test.js’).hello;

either way, lm will be ‘abc’ and hello will ‘hello’

or

var test = require(’./test.js’);

and then you can access the properties of test: test.lm and test.hello


#3

Read this: module.exports vs. exports. It might be helpful to you to understand the concept.