我正在调用三个函数,这些函数完成后,我希望自己的脚本自行关闭,但只是挂起。
我尝试过使函数基于异步/承诺,在每个“ mongodb”类型函数之后关闭数据库,并在函数内使用process.exit()作为最后一个调用函数的回调。
连接到(本地-非Atlas)数据库:
function insertJSON(db, dirBuf,collection, sourceFolder) {
var database = db.db('license-server')
var collection = database.collection(collection)
fs.readdir(dirBuf, function(err, files) {
if (err) {
console.log(err.message)
}
else {
files.forEach(function(filename) {
var text = fs.readFileSync(sourceFolder + filename);
var filecontents = JSON.parse(text)
//collection.insertOne(filecontents)
collection.findOne({"DisplayTitle" : filecontents.DisplayTitle, "NodeInformation" : filecontents.NodeInformation, "Date": filecontents.Date})
.then(function(result) {
if(result) {
console.log(`An Item could already be in the database: A file is unique if its display title, nodeinformation, and date are different.
the items display title is ${result.DisplayTitle}`)
return
}
else {
collection.insertOne(filecontents)
console.log(`Added ${filecontents.DisplayTitle} to database`)
}
})
.catch(function(error) {
console.log(error)
})
})
}
})
}
功能1:
function insertLicenses(db) {
// Set up GridFS to import .lic and .licx files into the database
var database = db.db('license-server')
var collection = database.collection('fs.files')
var bucket = new mongodb.GridFSBucket(database);
var dirBuf = Buffer.from('../license-server/private/licenses')
fs.readdir(dirBuf, function(err, files) {
if (err) {
console.log(err.message)
}
else {
files.forEach(function(filename) {
collection.findOne({"filename": filename}).
then(function(result) {
if(result) {
console.log(`The file ${filename} is already in the database`)
return
}
else {
fs.createReadStream('./private/licenses/' + filename).
pipe(bucket.openUploadStream(filename)).
on('error', function(error) {
assert.ifError(error)
}).
on('finish', function() {
console.log(`Uploaded ${filename}`)
})
}
})
})
}
})
// I tried calling db.close() here since this is the last function to be called. No luck.
}
功能2:
{{1}}
我猜想这与mongodb函数有其自身的关闭方式有关,但我似乎找不到以前尝试解决此问题时要寻找的东西。
预期结果应该是脚本自身关闭,实际结果是处理脚本。
答案 0 :(得分:1)
所有这些数据库调用都是异步的-运行此代码的结果是立即调用db.close
,然后在insertJSON
和insertLicenses
中进行工作。如果要使用async/await
重写它(并且还需要更新其他功能),则db.close
调用将关闭数据库,这将使脚本退出:>
await insertJSON(db, jsonfiles, 'requests', jsonfilesSource)
await insertJSON(db, issuedfiles, 'issuedLicenses', isssuedfilesSource)
await insertLicenses(db)
db.close()
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Introducing https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function