繁体   English   中英

Node.js-mysql连接无输出

[英]Node.Js - no output from mysql connection

抱歉,第一次使用nodejs

我已经在Linux机器上安装了nodejsnpm manager。 通过npm我安装了mysql模块,现在我尝试使用简单的代码测试mysql连接。 问题是-运行mysql相关代码时,没有输出输出到控制台!

资源:

var mysql = require("mysql");

console.log('1');

var connection = mysql.createConnection({
  host: "127.0.0.1",
  user: "xxx",
  password: "xxxx",
  database: "xxx",
  port: 3306

});

console.log('2');

connection.connect(function(err){
    if(err){
        console.log('Error connecting to Db');
        return;
    }

    console.log('Connection established');
});

console.log('3');

connection.end(function(err) {
    console.log('Connection closed');
});

console.log('4');

process.exit();

输出为1234:

在此处输入图片说明

以下是已安装的模块:

在此处输入图片说明

所以我的问题是-为什么没有消息来自mysql连接? 我试图故意输入错误的连接详细信息-没有消息产生。

我也尝试将节点运行为sudo ,还尝试运行nodejs index.js而不是node index.js 哦,我也尝试安装并使用nodejs-mysql模块而不是mysql 似乎没有任何作用。

您正在编写异步代码,因此您需要等待这些操作完成后才能强制终止该进程。

实际上,您的意思是“执行此操作,执行此操作,执行此操作,然后稍后再回来找我。也请立即关闭所有内容。”

删除process.exit调用或将其移动到回调函数中,以便在正确的时间触发它:

var connection = mysql.createConnection({
  ...
});

console.log('2');

connection.connect(function(err){
  if(err) {
    console.log('Error connecting to Db');
    return;
  }

  console.log('Connection established');

  console.log('3');

  connection.end(function(err) {
    console.log('Connection closed');
    console.log('4');

    process.exit();
  });
});

这种激进的嵌套和重新嵌套是存在promise之类的原因。 Bluebird是用于实现和使用它们的出色库,并且被Sequelize等数据库包装程序用来使您的代码井井有条。

暂无
暂无

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

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