我遇到NodeJS问题。我想创建一个服务器端脚本,它将在其目录中获取一个新文件的文件名,并自动将其保存到数据库中。
这是我的代码:
const path = require('path')
//mysql Connecion
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "sms"
});
//con checking if the database is connected
con.connect(function(err) {
if (err) throw err;
//watchfile directory if there's new added file
var chokidar = require('chokidar');
var watcher = chokidar.watch('texts/', {ignored: /^\./, persistent: true});
//for getting the filename only
var fs = require('fs');
var testFolder = 'texts/';
watcher.on('add', function(filePath) {
var filename = path.basename(filePath);
var selectSql = 'SELECT count(filename) AS matchingEntriesCount FROM txtfilename WHERE filename="${filename}"';
con.query(selectSql, (err, results, fields) => {
// TODO: Catch the error
console.log(err);
var matchingEntriesCount = results[0].matchingEntriesCount
if (matchingEntriesCount == 0) {
console.log('File', filename, 'has been added');
// TODO: Do your insert query
var insertsql = "INSERT INTO txtfilename (filename) VALUES ('"+ filename +"')";
con.query(insertsql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
}
});
});
});
希望有人会帮我解决我的问题..谢谢。
答案 0 :(得分:1)
watcher
是函数connect
的局部变量,因此在退出函数时会将其删除。如果您希望代码有效,则需要使观察者成为全局变种。
当您致电con.query
时,无论如何都会隐式建立连接,因此您可以完全删除con.connect
。