简体   繁体   中英

Node.Js - no output from mysql connection

Sorry in advance - using nodejs for the first time..

I have installed nodejs and npm manager on linux machine. Through the npm I installed mysql module and now I try to test the mysql connection using the simple code. The problem is - no output is printed to the console, when the mysql related code is run!

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:

在此处输入图片说明

Here are installed modules:

在此处输入图片说明

So my question is - why are there no messages coming from mysql connection? 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 . Oh, and I also tried to install and use nodejs-mysql module instead of 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:

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. Bluebird is a great library for implementing and using these and is used by database wrappers like Sequelize to keep your code organized.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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