Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

192
Visualizações
node script not getting completed

I have a simple script to dump data into db, which I am using in conjunction of npm script. I am trying to dump data into db before my node application server starts. However the dump script doesn't complete ever and hence the server start script doesn't start. Here is my dump script -

const mongodb = require('mongodb')
  , fs = require('fs')
  , MongoClient = mongodb.MongoClient
  , client = new MongoClient(`mongodb://localhost:27017/admin`, { useUnifiedTopology: true })
  , docs = fs.readFileSync(`${process.cwd()}/app/scripts/records.json`)

client.connect().then(cl => {
  const dbObj = cl.db('dumpdb')
  dbObj.collection(`loc_biz_hrs`).insertMany(JSON.parse(docs)).then(result => {
    console.log(`${result.insertedCount} records inserted`)
  })
})

and here is how I am trying to execute it using npm script -

"scripts": {
    "start": "node app/scripts/records.js && nodemon --exec babel-node index.js",
    "test": "test"
}

It just displays in terminal 35755 records inserted and gets stuck in there and doesn't execute the index.js part of the script.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

try using concurrently npm package npm i concurrently


"scripts": {
    "start": "react-scripts start",
    "dev": ""concurrently \"node app/scripts/records.js\" \"nodemon --exec babel-node index.js\""
}
over 4 years ago · Santiago Trujillo Relatório

0

You are not closing the connection using cl.close(), so try this:

const mongodb = require('mongodb')
  , fs = require('fs')
  , MongoClient = mongodb.MongoClient
  , client = new MongoClient(`mongodb://localhost:27017/admin`, { useUnifiedTopology: true })
  , docs = fs.readFileSync(`${process.cwd()}/app/scripts/records.json`)

client
  .connect()
  .then(cl => {
    const dbObj = cl.db('dumpdb');

    dbObj
      .collection(`loc_biz_hrs`)
      .insertMany(JSON.parse(docs))
      .then(result => {
        console.log(`${result.insertedCount} records inserted`);
        cl.close();
      }).catch(error => {
        console.log(error);
        cl.close();
      })
  })
  .catch(error => {
    console.log(error);
  });
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda