Error while reading a file and running line by line in the nodejs

Asked

Viewed 30 times

0

Good afternoon, I am creating a code to read a text file and run line by line using the execa packages and list in the nodejs, but it is checking the task function first then executes the commands. Code is like this:

async function print(file_path, callback) {
  fs.readFileSync(file_path.toString() , 'utf8', function(err, texto) {
    if (err){
      return callback (err);
    }else {
      var linhas = texto.split(/\rs?\n/);
      linhas.forEach(function(linha){
        const pRetry = require('p-retry');
          const run = async () => {
            const results = await execa(linha);
            return results;
          };
          (async () => {
            console.log(pRetry(run, {retries: 5}));
          })();
      });
    }
  })
}
const tasks = new Listr([
    {
      title: chalk.green('Criação de diretorios'),
      task: () => print('teste.txt',function(texto,err){
        if (err) {
          throw new Error('Deve ser executado com root')
        }
      })
    },

]); tasks.run(). catch((err: any) => { process Exit.(); });

out is like this:

inserir a descrição da imagem aqui

  • If he’s showing off Promise { <pending> } is pq has something async that you’re not treating.

  • Instead of console.log(pRetry(run, {retries: 5})); if you do js&#xA;const result = await run ();&#xA;console.log(pRetry(result, { retries: 5 }))&#xA;&#xA;

  • I made the change that you said and no longer appears Promise {<pending>} , but in the execution of the tasks it already gives the ckeck in all task as done and runs in the background.. wanted him to execute a task and only after he finished calling the next task.

  • https://oieduardorabelo.medium.com/javascript-armadilhas-do-asyn-await-em-loops-1cdad44db7f0 . That is to have the async part inside a loop. It explains how to leave sequential respecting the array order.

1 answer

0

Good afternoon; I managed to solve my problem, what was happening is that I was passing the execa along with the function, and that actually had to put the execa inside the listr.. follows the example below.

function print(file_path: string) {
  try {
    const data = fs.readFileSync(file_path.toString(), "utf8");
    var linhas = data.split(/\r?\n/);
    return data;
  } catch (err) {
    console.log(err);
  }
}


const task = new Listr([
  {
    title: chalk.green('Criação dos diretorios'),
    task: () => execSync(print('c:/teste.txt'))
  },
]);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.