一种批量将本地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,
};