MM Furkan
MM Furkan

Reputation: 53

Node js exporting Module return an undefined value in another file where I import it

I am getting undefined in console.log. Why? How to correct it and, I have to do it on this why only.

This is code for demofile:

exports.selectorquery = function() {
    var conn = "New connection";
    var nt = "Last Connect";

    function myFunc(arg) {
        return conn;    
    }

    setTimeout(myFunc, 3500, 'funky');
}

This is for run.js:

var go = require('./demofile.js');
console.log(go.selectorquery());

Upvotes: 2

Views: 45

Answers (2)

Steve Holgado
Steve Holgado

Reputation: 12089

Your selectorquery function does not return anything. Therefore, undefined is returned.

The function myFunc is scheduled for execution later but your console log will log the result of selectorquery, which is undefined.

Adding a console log to myFunc will log after the specified timeout:

function myFunc(arg) {
  console.log(conn);
  return conn;
}

Upvotes: 0

Harshal Yeole
Harshal Yeole

Reputation: 5003

YOur function is not returning anything:

Here's how you can do it.

demofile.js

exports.selectorquery = function (callback) {
    var conn = "New connection";
    var nt = "Last Connect";
    function myFunc(arg) {
        callback(null, conn);

    }
    setTimeout(myFunc, 3500, 'funky');
}

run.js

const go = require('./demofile');

go.selectorquery(function(err, data) {
    console.log(data);
});

Now run:

node run.js

It should log

New connection

Read more: NodeJS Export and Import Modules

Hope it solved your query.

Upvotes: 1

Related Questions