需要来自另一个文件= nodejs的函数和变量

时间:2022-05-15 15:59:52

I am trying to offload some of the bulk from my app and came across this issue.

我试图从我的应用程序卸载一些批量,并遇到了这个问题。

Here is my code:

这是我的代码:

// foo.js:

var mysql = require('mysql');

module.exports = {
  home: function () {
    return mysql.createConnection({
      host : '2.2.2.2',
      user: 'admin',
      password: 'xxxxxx',
      database : 'mlb'
    });
  }

// bar.js:

var dbConnect = require('./foo.js');

dbConnect.home.query('SELECT * from batters;', function(err, res, body) {
  if (err) throw err;
  var string_data = JSON.stringify(res);
  var jsonData = JSON.parse(string_data);
  console.log(jsonData);
});

The error i receive is undefined is not a function... What am I doing wrong?

我收到的错误未定义不是一个函数......我做错了什么?

2 个解决方案

#1


3  

Wouldn't home need to be like this:
dbConnect.home().query

不想回家需要像这样:dbConnect.home()。query

#2


0  

I needed to instantiate the imported function before calling its method.

我需要在调用其方法之前实例化导入的函数。

Correct code for bar.js is:

bar.js的正确代码是:

var dbConnect = require('./test.js');

var connection = dbConnect.home();

connection.query('SELECT * from batters;', function(err, res, body) {
  if (err) throw err;
  var string_data = JSON.stringify(res);
  var jsonData = JSON.parse(string_data);
  console.log(jsonData);
});

#1


3  

Wouldn't home need to be like this:
dbConnect.home().query

不想回家需要像这样:dbConnect.home()。query

#2


0  

I needed to instantiate the imported function before calling its method.

我需要在调用其方法之前实例化导入的函数。

Correct code for bar.js is:

bar.js的正确代码是:

var dbConnect = require('./test.js');

var connection = dbConnect.home();

connection.query('SELECT * from batters;', function(err, res, body) {
  if (err) throw err;
  var string_data = JSON.stringify(res);
  var jsonData = JSON.parse(string_data);
  console.log(jsonData);
});