简体   繁体   English

将SELECT sql变量数组从一个文件发送到Node.js中的另一个文件

[英]Sending a SELECT sql variable array from one file to another in Nodejs

I'm trying to module.export "rows" from this function over to anotherfile.js 我正在尝试从此功能将module.export“行”转移到anotherfile.js

"mysql.js" “ mysql.js”

const gameserverShow = function () {
    con.query(`SELECT * FROM gameservers`, (err, rows) => {
        if (err) throw err;
        return rows;
    });
 }

module.exports.gameserverShow = gameserverShow;

I tried to make a "foreach loop" into a array and send it over, but everytime I try to console.log it, it return "undefined". 我试图将“ foreach循环”放入数组并发送过来,但是每次我尝试console.log时,它都会返回“ undefined”。 is there a different/correct way to do it? 有其他/正确的方法吗?

"anotherfile.js" “ anotherfile.js”

const mysqlcon = require("./mysql.js");
      if (args[0] == 'show') {
            mysqlcon.gameserverShow();
            console.log(mysqlcon.gameserverShow.rows);
      }

You are doing that in a wrong way. 您这样做的方式有误。 You should first read how javascript function calls, callbacks works and how to handle async tasks in javascript. 您首先应该阅读javascript函数调用,回调的工作方式以及如何处理javascript中的异步任务。 You have to handle it asynchronously with callbacks or promise. 您必须使用回调或Promise异步处理它。 As you are using callbacks here following is basic code for that. 当您在这里使用回调时,以下是该代码的基本代码。

const gameserverShow = function (callback) {
    con.query(`SELECT * FROM gameservers`, (err, rows) => {
        if (err) callback(err);
        callback(null, rows);
    });
 }

module.exports.gameserverShow = gameserverShow;

And in Another file 并在另一个文件中

const mysqlcon = require("./mysql.js");
      if (args[0] == 'show') {
            mysqlcon.gameserverShow((error, rows) => {
               console.log(rows);
            });
      }

You can search how to do that with promises. 您可以搜索如何用诺言做到这一点。 There are many questions about that here. 这里有很多问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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