提问者:小点点

如何将节点包中的函数应用到一个目录中的所有文件中?


我安装了mammoth.js模块,它将docx转换为html。 我可以用一个文件。

如何将同一模块用于特定文件夹中的所有文件? 我试图保存一个输出html文件,同时保留原始名称(当然不是扩展名)。 可能我需要一些其他的包裹。。。 下面的代码用于所需目录中的单个文件:

var mammoth = require("mammoth");

    mammoth.convertToHtml({path: "input/first.docx"}).then(function (resultObject) {
        console.log('mammoth result', resultObject.value);
      });

系统为win64


共1个答案

匿名用户

这样的办法应该管用

const fs = require('fs')
const path = require('path')
const mammoth = require('mammoth')

fs.readdir('input/', (err, files) => {
  files.forEach(file => {
    if (path.extname(file) === '.docx') {
      // If its a docx file
      mammoth
        .convertToHtml({ path: `input/${file}` })
        .then(function(resultObject) {
          // Now get the basename of the filename
          const filename = path.basename(file)
          // Replace output/ with where you want the file
          fs.writeFile(`output/${filename}.html`, resultObject.value, function (err) {
            if (err) return console.log(err);
          });
        })
    }
  })
})