使用node.js将数据插入到mysql中,但脚本挂起

我有这个脚本来读取文件,然后将数据插入到MySQL表中。 该脚本的作品,但它挂起,所以我不得不按CTRL-C停止脚本。 但脚本应该正常停止,我必须改变什么?

var fs = require('fs'); var filename; var myGID; filename = "data/insertUser1_next.json"; function get_line(filename, line_no, callback) { fs.readFile(filename, function (err, data) { if (err) throw err; // Data is a buffer that we need to convert to a string // Improvement: loop over the buffer and stop when the line is reached var lines = data.toString('utf-8').split("\n"); if(+line_no > lines.length){ return callback('File end reached without finding line', null); } // lines callback(null, lines[0], lines[1], lines[2], lines[3]); }); } get_line(filename, 0, function(err, line, line2, line3, line4){ line = line.replace(/(\r\n|\n|\r)/gm,""); line2 = line2.replace(/(\r\n|\n|\r)/gm,""); line3 = line3.replace(/(\r\n|\n|\r)/gm,""); /*line4 = line4.replace(/(\r\n|\n|\r)/gm,"");*/ console.log('The line: ' + line); console.log('The line2: ' + line2); console.log('The line3: ' + line3); console.log('The line4: ' + line4); var post = {gid: line, uid: line2}; var post2 = {uid: line2, displayname: line3, password: line4}; var mysql = require('mysql'); var db_config = { host : '123.456.789.012', user : 'user', password : 'password', database : 'maindata' }; var con = mysql.createPool(db_config); con.getConnection(function(err){ if (err) { console.log(err); return; } con.query('INSERT INTO group_user SET ?', post, function(err, result) { if (err) { console.log(err); return; } }); con.query('INSERT INTO users SET ?', post2, function(err, result) { if (err) { console.log(err); return; } }); }); }); 

在这里你可以看到发生了什么:

当你使用池时,你必须结束所有连接,否则Node.js事件循环将保持活动状态,直到MySQL服务器closures连接。 这通常是在脚本中使用池或尝试正常closures服务器时完成的。 要结束池中的所有连接,请使用池上的end方法:

 pool.end(function (err) { // all connections in the pool have ended }); 

因此,如果在查询完成后放置con.end() ,脚本将正常终止

以下语句将closures连接,确保处理队列中的所有查询。 请注意,这是一个callback函数。

 connection.end(function(err){ // Do something after the connection is gracefully terminated. }); 

嘿,我build议永远安装,并启动节点servers.js永远不需要任何terminal打开。

而你需要closures你的MySQL连接到最后来阻止你挂起问题,我想。

 npm install -g forever npm install forever //FOR your Problem con.end(function(err){ // Do something after the connection is gracefully terminated. }); con.destroy(); 

以下语句将closures连接,确保处理队列中的所有查询。 请注意,这是一个callback函数。

 connection.end(function(err){ // Do something after the connection is gracefully terminated. }); 

以下语句将终止分配的套接字并立即closures连接。 也没有更多的callback或事件触发的连接。

  connection.destroy();