javascript - how to export function in nodejs - Stack Overflow

i am new in nodejs,i need to export function in nodejs db_function.js filevar mysql = require('my

i am new in nodejs,i need to export function in nodejs
db_function.js file

var mysql = require('mysql'); 
var config  = require('./config.js');
var con = config.conn;

exports.is_valid_IP = {
 function(IP,callback)
  {
    con.connect(function(err) {
      if (err) throw err;
      con.query("SELECT * FROM server_master", function (err, result, fields) {
        if (err) throw err;
        callback(result);
      });
    });
  }
};

app.js file

  app.get('/test',function(req,res){
  var IP = 1;
  db.is_valid_IP(IP,function(result){
    console.log(result);
  });
});

It Show error Cannot call method 'connect' of undefined

i am new in nodejs,i need to export function in nodejs
db_function.js file

var mysql = require('mysql'); 
var config  = require('./config.js');
var con = config.conn;

exports.is_valid_IP = {
 function(IP,callback)
  {
    con.connect(function(err) {
      if (err) throw err;
      con.query("SELECT * FROM server_master", function (err, result, fields) {
        if (err) throw err;
        callback(result);
      });
    });
  }
};

app.js file

  app.get('/test',function(req,res){
  var IP = 1;
  db.is_valid_IP(IP,function(result){
    console.log(result);
  });
});

It Show error Cannot call method 'connect' of undefined

Share Improve this question edited Jan 17, 2018 at 12:27 Mahesh Jagdale asked Jan 17, 2018 at 12:07 Mahesh JagdaleMahesh Jagdale 1742 silver badges10 bronze badges 5
  • 1 You export correctly. con is undefined in your db_function.js – Adelin Commented Jan 17, 2018 at 12:09
  • i declared var con = config.conn; – Mahesh Jagdale Commented Jan 17, 2018 at 12:11
  • And it didn't occur to you that con is probably undefined? – dfsq Commented Jan 17, 2018 at 12:13
  • @MaheshJagdale I trust what Javascript says. Can you show us your entire db_function? Maybeyou declare con too late, and JS already tries to access it – Adelin Commented Jan 17, 2018 at 12:14
  • con is declared in app.js, yet you try to access it in db_function.js. Even if you call your function in app.js, javascript still (thankfully) maintains the correct context for code evaluation and execution – Adelin Commented Jan 17, 2018 at 12:20
Add a ment  | 

3 Answers 3

Reset to default 5

You can export like this:

enter code here
var funName = function() {
}
module.exports = funName;

Let me sum up the ments:

You export correctly. That's not where your problem lies

The issue occurs due to the fact that, in db_function.js, con is not defined.

Even if you declare it in app.js, javascript will correctly isolate the two contexts (app.js from db_function.js).

We talk about different files here, but the context preservation can occur even in the same files

var functionOne = function(){
   var con = 1;
}
console.log(con) // undefined err, because con is declared inside the function

even if you call the function

var functionOne = function(){
   var con = 1;
}
functionOne();
console.log(con) // undefined err, because con is long gone as soon as function returns

con will live only until the function returns.

if you want to tell is_valid_IP what connection to use, you can simply update your code as follows:

db_function.js file

exports.is_valid_IP = {
 function(IP,con,callback)
  {
    con.connect(function(err) {
      if (err) throw err;
      con.query("SELECT * FROM server_master", function (err, result, fields) {
        if (err) throw err;
        callback(result);
      });
    });
  }
}; 

And then use it in app.js file as follows:

app.get('/test',function(req,res){
  var IP = 1;
  db.is_valid_IP(IP,con,function(result){
    console.log(result);
  });
});

Let's simplify the issue, as the title of the question suggests, "how to export function in nodejs". If we only consider how to export function in Node.js, we can do as below:

./db_function.js (We export function isValidIp):

'use strict';

module.exports.isValidIp = function(ip, callback) {
    console.log("Check if IP is valid.");
    callback();
};

./app.js

'use strict';

var db = require('./db_function');
// require() returns the object that module.exports references

db.isValidIp('127.0.0.1', function(){
    console.log('Called back.');
});

Run it with mand node app.js, you'll get:

Check if IP is valid.
Called back.

One caveat

./db_function.js (This version does not work):

'use strict';

exports = { 
    isValidIp: function(ip, callback) {
        console.log("Check if IP is valid.");
        callback();
    }
};

You'll get TypeError:

TypeError: db.isValidIp is not a function

That is because require() return module.exports, rather than exports. exports is just a shorthand of module.exports. If you point exports to a different object, you should update module.exports as well. The following version will work:

'use strict';

exports = { 
    isValidIp: function(ip, callback) {
        console.log("Check if IP is valid.");
        callback();
    }
};

module.exports = exports;

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744964586a4603597.html

相关推荐

  • javascript - how to export function in nodejs - Stack Overflow

    i am new in nodejs,i need to export function in nodejs db_function.js filevar mysql = require('my

    1天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信