欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 艺术 > 一种批量将本地word文档转成html的方法【基于node.js】

一种批量将本地word文档转成html的方法【基于node.js】

2025/3/15 11:33:16 来源:https://blog.csdn.net/weixin_61241731/article/details/146100218  浏览:    关键词:一种批量将本地word文档转成html的方法【基于node.js】

如果你有一种需求需要批量转换本地的word文档成html,简单—安排上

第一步:将所有需要转换的文档放入同一个文件夹内

比如文件夹命名为batch

第二步:使用fs的readdir方法阅读文件夹中的文档

let files = await fs.readdir(__dirname + '/batch');
let fileArr = []

遍历

for (const file of files) {if(file.endsWith('.docx')){const filePath = path.join(__dirname + '/batch', file);let data = await fs.readFile(filePath)}}

第三步:使用mammoth.convertToHtml将二进制文件转成html

let htmlText = await mammoth.convertToHtml({buffer: data})
let fileExt = {fileName:file,fileBuffer:htmlText.value}fileArr.push(fileExt)

完整代码为:

const Koa = require('koa');
const fs = require('fs').promises;
const app = new Koa();
const path = require('path')// 将docx文件转成html
const mammoth = require("mammoth");var saveDoc = async (ctx, next) => {let files = await fs.readdir(__dirname + '/batch');let fileArr = []for (const file of files) {if(file.endsWith('.docx')){const filePath = path.join(__dirname + '/batch', file);let data = await fs.readFile(filePath)try{let htmlText = await mammoth.convertToHtml({buffer: data})let fileExt = {fileName:file,fileBuffer:htmlText.value}fileArr.push(fileExt)}catch(err){console.log(err)}}}ctx.body = {code:'200',data:fileMap,msg:'成功'}
};module.exports = {'POST /saveDoc': saveDoc,
};

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词