如何将节点包中的功能应用于目录中的所有文件?

问题描述 投票:1回答:1

我已经安装了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

javascript node.js batch-processing mammoth
1个回答
0
投票

类似这样的方法应该起作用

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)
          fs.writeFile(`output/${filename}.html`, resultObject.value, function (err) {
            if (err) return console.log(err);
          });
        })
    }
  })
})
© www.soinside.com 2019 - 2024. All rights reserved.