读取目录中的 docx 文件并在节点中将内容连接在一起?

read docx files in a directory and concat the content together in node?

代码需要读取目录下的所有文件和return该目录下每个docx文件中的所有内容。

我正在使用 glob 和 mammoth 库分别读取目录和 docx 文件。但是我想将每个文件内容合并成一个更大的内容。但由于节点是异步的,我编写的代码会在读取每个文件之前将空内容传递给我。

var mammoth = require("mammoth");
var glob = require("glob");
function readAllFiles(dir){

  var data_collection = '';
  return new Promise(async(resolve, reject) => {
    // reading the directory
    glob(dir,  function (er, files) { 
      console.log(files);
      // for each file in the directory read its content
      _.map(files, function(file){
        mammoth.extractRawText({path: file})
            .then(function(result){
                var text = result.value; // The raw text
                var messages = result.messages;
                text = text.replace(/(^[ \t]*\n)/gm, "").replace('\r', '').replace('\n', '');
                console.log('extractRawText',text);
                // concat the small content into big content
                data_collection = data_collection + " "+text;
            })
            .done();
      });
      resolve(data_collection);
    });
  });
}

我该如何解决这个问题?

_.map 是同步的。它不会等待巨大的承诺来解决。 resolve(data_collection); 行将在 _.map 之后和巨大的承诺解决之前立即执行。这就是 data_collection 为空的原因。

你可以使用类似的东西,

var mammoth = require("mammoth");
var glob = require("glob");

function readAllFiles(dir){
  return new Promise((resolve, reject) => {
    glob(dir, (err, files) => {
      if(err) {
        return reject(err)
      }

      return Promise.all(files.map((file) => mammoth.extractRawText({ path: file })))
        .then((results) => {
          let data = ''
          results.forEach((result) => {
            const value = result.value.replace(/(^[ \t]*\n)/gm, "").replace('\r', '')
            data = data.concat(value)
          })
          resolve(data)
        })
        .catch(reject)
    })
  })
}

async function test() {
  const data = await readAllFiles('./test/**/*.docx') // All my docx files are in the test directory
  console.log(data) // Print data
}

test()

请注意,这将并行执行 mammoth.extractRawText 函数调用。如果你需要限制同时并行调用的数量,你可以使用类似 async.mapLimit.