首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将node包中的函数应用于一个目录下的所有文件?

如何将node包中的函数应用于一个目录下的所有文件?
EN

Stack Overflow用户
提问于 2020-06-05 21:28:26
回答 1查看 58关注 0票数 1

我已经安装了将docx转换为html的mammoth.js模块。我可以在一个文件中使用它。

如何对特定文件夹中的所有文件使用相同的模块?我正在尝试保存输出的html文件,同时保留原始名称(当然不是扩展名)。也许我需要一些其他的包。以下代码用于所需目录中的单个文件:

代码语言:javascript
复制
var mammoth = require("mammoth");

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

系统为win64

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-05 21:57:19

像这样的东西应该是可行的

代码语言:javascript
复制
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);
          });
        })
    }
  })
})
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62216455

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档