简体   繁体   English

Node.js-mysql连接无输出

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

Sorry in advance - using nodejs for the first time.. 抱歉,第一次使用nodejs

I have installed nodejs and npm manager on linux machine. 我已经在Linux机器上安装了nodejsnpm manager。 Through the npm I installed mysql module and now I try to test the mysql connection using the simple code. 通过npm我安装了mysql模块,现在我尝试使用简单的代码测试mysql连接。 The problem is - no output is printed to the console, when the mysql related code is run! 问题是-运行mysql相关代码时,没有输出输出到控制台!

source: 资源:

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();

The output is 1234: 输出为1234:

在此处输入图片说明

Here are installed modules: 以下是已安装的模块:

在此处输入图片说明

So my question is - why are there no messages coming from mysql connection? 所以我的问题是-为什么没有消息来自mysql连接? I tried to enter incorrect connection details on purpose - no messages were produced. 我试图故意输入错误的连接详细信息-没有消息产生。

I also tried running node as sudo and also tried running nodejs index.js instead of node index.js . 我也尝试将节点运行为sudo ,还尝试运行nodejs index.js而不是node index.js Oh, and I also tried to install and use nodejs-mysql module instead of mysql . 哦,我也尝试安装并使用nodejs-mysql模块而不是mysql Nothing seems to be working. 似乎没有任何作用。

You're writing asynchronous code, so you need to wait for those operations to complete before you force kill the process. 您正在编写异步代码,因此您需要等待这些操作完成后才能强制终止该进程。

What you're essentially saying is "Do this, do this, do this, and get back to me later. Also shut everything down right now." 实际上,您的意思是“执行此操作,执行此操作,执行此操作,然后稍后再回来找我。也请立即关闭所有内容。”

Remove the process.exit call or move it inside a callback function so it's triggered at the right time: 删除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();
  });
});

This aggressive nesting and re-nesting is why things like promises exist. 这种激进的嵌套和重新嵌套是存在promise之类的原因。 Bluebird is a great library for implementing and using these and is used by database wrappers like Sequelize to keep your code organized. Bluebird是用于实现和使用它们的出色库,并且被Sequelize等数据库包装程序用来使您的代码井井有条。

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

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