代码之家  ›  专栏  ›  技术社区  ›  user824624

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

  •  -1
  • user824624  · 技术社区  · 6 年前

    需要该代码来读取目录中的所有文件,并返回该目录中每个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);
        });
      });
    }
    

    我该如何解决这个问题?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Mayur    6 年前

    resolve(data_collection); _.map

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

    请注意,这将并行执行mammath.extractrawtext函数调用。如果需要限制同时进行的并行调用的数量,可以使用 async.mapLimit