五分钟速成!用nodejs将doc文件转成html

JavaScript09

五分钟速成!用nodejs将doc文件转成html,第1张

经常有一些将doc文件转换成HTML的需求,比如说明、协议之类的。虽然有 https://word2cleanhtml.com/ 这种神器,像下图这样可以直接将doc内容粘贴到剪贴板上,即可得到对应的html。但是,复制粘贴也是个体力活,如果一天突然要做10个这样的文档,可能真的要抓狂了。基于此目的,一起来做个脚本一键傻瓜式生成HTML吧。 首先,我们脚本的主角是 mammoth ,这个东西可以读取doc文档,并把内容给转换出来。 准备工作就是安装示例文档里的两个依赖 文档里给的转换html的示例是这样的。 可以试一试,会发现做出来的html效果会生成strong、p、tr、td这种标签,套上head、body、css之后页面就非常完整了,可是一些特殊的效果,比如说下划线u就没有。 怎么让他们出现呢?可以直接在文档里搜下划线的英文Underline,找到这条说明 原来在转换的过程中,下划线被忽略了,文档里也给了解决方法。可以显式地设置下划线转换成的标签去让下划线生效,像这样。 然后,我发现,生成的页面没有带class样式。其实在doc文档里面,有些行是居中效果的,如何做到居中效果在页面里也生效呢? 我们在template里写一个.center样式,然后options里试一试这个功能。 以下是完整的生成脚本。 这样一来,就算一天十个文档也是分分钟的事情了。

var http = require("http"),

url = require("url"),

path = require("path"),

fs = require("fs")

http.createServer(function (req, res) {

var pathname=__dirname+url.parse(req.url).pathname

if (path.extname(pathname)=="") {

pathname+="/"

}

if (pathname.charAt(pathname.length-1)=="/"){

pathname+="index.html"

}

path.exists(pathname,function(exists){

if(exists){

switch(path.extname(pathname)){

case ".html":

res.writeHead(200, {"Content-Type": "text/html"})

break

case ".js":

res.writeHead(200, {"Content-Type": "text/javascript"})

break

case ".css":

res.writeHead(200, {"Content-Type": "text/css"})

break

case ".gif":

res.writeHead(200, {"Content-Type": "image/gif"})

break

case ".jpg":

res.writeHead(200, {"Content-Type": "image/jpeg"})

break

case ".png":

res.writeHead(200, {"Content-Type": "image/png"})

break

default:

res.writeHead(200, {"Content-Type": "application/octet-stream"})

}

fs.readFile(pathname,function (err,data){

res.end(data)

})

} else {

res.writeHead(404, {"Content-Type": "text/html"})

res.end("<h1>404 Not Found</h1>")

}

})

}).listen(8080, "127.0.0.1")

console.log("Server running at http://127.0.0.1:8080/")