javascript - 我的 Node 脚本在函数完成后挂起

标签 javascript node.js mongodb

我正在调用三个函数,在完成这些函数后,我希望我的脚本自行关闭,但它只是挂起。

我尝试使函数基于异步/ promise ,在每个“mongodb”类型函数之后关闭数据库,并在函数中使用 process.exit() 作为最后调用的函数的回调。

连接到(本地 - 非 Atlas)数据库:

MongoClient.connect(local, {useNewUrlParser: true, useUnifiedTopology: true}, function(err, db) {
  if (err) {
    console.log(err)
  }
  else {
    console.log('Connected to MongoDB...')
    //Read in data from jsonfiles and store each file's contents into the database : This is where the functions are being called... within a successful connect to the MongoDB
    insertJSON(db, jsonfiles, 'requests', jsonfilesSource)
    insertJSON(db, issuedfiles, 'issuedLicenses', isssuedfilesSource)
    insertLicenses(db)
  }
  db.close()
})

函数1:

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)
          })
      })
    }
  })
}

函数2:

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.
}

我猜测这与 mongodb 函数有自己的关闭方式有关,但我似乎找不到我在之前尝试解决此问题时所寻找的内容。

预期结果应该是脚本自行关闭,实际结果是处理脚本。

最佳答案

所有这些数据库调用都是异步的——此代码运行的结果是立即调用 db.close,然后在 insertJSON 中执行工作插入许可证。如果您要重写它以使用 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

关于javascript - 我的 Node 脚本在函数完成后挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58204633/

相关文章:

javascript - 如何在鼠标滚动上加载消息?

javascript - indexOf 取决于两个键

在 FireFox 之外进行 Javascript 调试

json - 访问 json 的属性

node.js - Git 忽略 mongod.log

javascript - 对于空字符串,如何将 parseInt 中的 NaN 转换为 0?

javascript - closure-compiler-js 和 grunt

node.js - 在 Mongoose 模型中使用 id 属性有危险吗?

java - 如何使用 Java 中的时间戳过滤器在 mongodb 中进行地理空间查询?

node.js - 如何使用 serverless-step-functions 插件中的定义调​​用 AWS Step Function?