簡體   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