Как я могу установить таймаут для этой функции в node js? - PullRequest
0 голосов
/ 21 февраля 2020

У меня есть эта функция из модуля asyn c, который читает из массива входных файлов, таких как:

inputs: ['file1.txt', 'file2.txt']
 map(inputs, fs.readFile,
   (err, contents) => {
      if (err) console.log('Error: ' + err);
      else {
        const data = contents.reduce((a, b) => a + b);
        fs.writeFile(output, data, () => console.log(`Output in file '${output}'`)
        );
      }
   }
);

Как я могу установить тайм-аут для вызова fs.readFile? я хочу, чтобы это было выполнено через 3 секунды, например. Я пытался это, например, но это не работает, я думаю, это проблема синтаксиса, что я не пишу это так, как должно:

map(inputs, setTimeout(fs.readFile,3000),
       (err, contents) => {
          if (err) console.log('Error: ' + err);
          else {
            const data = contents.reduce((a, b) => a + b);
            fs.writeFile(output, data, () => console.log(`Output in file '${output}'`)
            );
          }
       }
    );

Это должно быть легко, но я застрял. Может быть, я не могу поставить тайм-аут внутри функции карты? я должен создать новую функцию, и вместо вызова fs.readFile я вызываю свою функцию? Заранее спасибо.

1 Ответ

0 голосов
/ 21 февраля 2020

Даже если вы найдете правильное время для этих файлов, оно будет прерываться всякий раз, когда содержимое файла будет меняться, и идея добавления тайм-аута - это полный антипаттерн в node.js.

Если файлы не являются огромными, вы можете прочитать их все и объединить потом:

const { promisify } = require('util');
const fs = require('fs');
// Create Promise versions of the fs calls we will need
const readFile = promisify(fs.readFile);
const writeFile = promisify(fs.writeFile);

/**
 * @param {string[]} files - Paths to the files to concatene
 * @param {string} destination - Path of the concatenated file
 */
async function concat(files, destination) {
    // Read all files, Promise.all allow to have all operation happening in parallel
    const contents = await Promise.all(files.map(readFile));
    // content.join('') may not work as you want, replace it with whatever concatenation you need
    return writeFile(destination, contents.join(''));
}

Если вы не можете сохранить более одного файла за раз, вы можете добавлять их один за другим.

const fs = require('fs');
const { promisify } = require('util');
const readFile = promisify(fs.readFile);
const appendFile = promisify(fs.appendFile);

/**
 * @param {string[]} files - Paths to the files to concatene
 * @param {string} destination - Path of the concatenated file
 */
async function concat(files, destination) {
    // For each file
    for(const file of files) {
        // Read it
        const content = await readFile(file);
        // Append at the end of concatenated file
        await appendFile(destination, content);
    }
}

Не тестировал код, возможно, синтаксические ошибки повсюду, но вы должны понять,

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...