nodejs实现解析chm文件列表,无需转换为PDF文件格式,在线预览chm文件以及目录,不依赖任何网页端插件

简介: nodejs实现解析chm文件列表,无需转换为PDF文件格式,在线预览chm文件以及目录,不依赖任何网页端插件



特性:

1、支持任意深度的chm文件解析

2、解析后内容结构转换为tree数据呈现

3、点击树节点可以在html实时查看数据

4、不依赖任何浏览器端插件,兼容性较好

nodejs端核心代码

const $g = global.SG.$g, fs = global.SG.fs, router = global.SG.router, xlsx = global.SG.xlsx;
module.exports = global.SG.router;
let webRootPath = 'http://127.0.0.1:9999/chm/';//测试环境chm文件根目录
//上传单个文件(all方法支持POST、GET、PUT、PATCH、DELETE传参方式)
let uploadFileName = '';//获取上传后的文件名
router.all(
    "/chm/upload",//接口路径
    $g.dir.upload(
        "./upload",//存储临时上传文件的路径
        ({ fileName, } = {}) => { uploadFileName = fileName; }).single("file"),//上传单个文件
    (req, res) => {
        // 开始解压上传的upload文件----------------------------------------
        let cp = require('child_process');
        cp.exec("reg query HKEY_CLASSES_ROOT\\360zip\\shell\\open\\command /ve", function (e, stdout, stderr) {
            let rootPath = `${__dirname.split('\\').slice(0, -3).join('\\')}`;
            let uploadFolderPath = `${rootPath}\\upload\\${uploadFileName}`;
            let targetFolderPath = `${rootPath}\\chm\\${uploadFileName}`;
            let str = stdout.match(/\"([^\"]+)\"/)[0];
            if (str) {
                // console.log('已经找到360zip程序,详细地址为:'+str);
                cp.exec(`${str} -x ${uploadFolderPath} ${targetFolderPath}`, { encoding: 'binary' }, function (e, stdout, stderr) {
                    // 遍历读取目录里面的文件----------------------------------------
                    let files = [];
                    let walker = require('walk').walk(targetFolderPath, { followLinks: false });
                    walker.on('file', function (roots, stat, next) {
                        if (stat.name.includes(`.hhc`)) {
                            let hhcFilePath = `${roots}/${stat.name}`;
                            files.push(hhcFilePath);
                            fs.readFile(hhcFilePath, 'utf-8', (err, data) => $g.json.res(req, res, "chm文件解析成功", {
                                htmPath: `${webRootPath}${uploadFileName}/`,
                                hhcFilePath: `${webRootPath}${uploadFileName}/${stat.name}`,
                                hhcData: data,
                            }, true));
                        } else next();
                    });
                    walker.on('end', function () {
                        files.length === 0 && $g.json.res(req, res, "没有找到hhc文件,请仔细检查chm文件是否正确!", { targetFolderPath }, false);
                    });
                });
            } else {
                console.log('没有找到360zip程序,无法完成解压缩功能,请在服务器端安装360zip软件!');
            }
        });
    }
);

vue前端核心代码

<template>
    <div :class="$options.name">
        <div class="sg-left " v-loading="loading">
            <!-- 树节点 -->
            <div class="tree-header">
                <!-- 树节点 -->
                <div class="tree-header">
                    <div class="sg-left ">
                        <el-tooltip popper-class="sg-el-tooltip" :enterable="false" effect="dark" :content="`支持拖拽到树上传文件`"
                            placement="top-start">
                            <el-button type="text" icon="el-icon-upload" size="mini"
                                @click="d => $refs.sgUpload.triggerUploadFile()">
                                上传chm文件
                            </el-button>
                        </el-tooltip>
                    </div>
                    <div class="sg-right ">
                    </div>
                </div>
            </div>
            <div class="tree-body" @click="treeData.length === 0 ? $refs.sgUpload.triggerUploadFile() : ''">
                <el-tree ref="tree" @current-change="current_change" :data="treeData"
                    :props="{ label: 'Name', children: 'children' }" :icon-class="'folder-tree-node'" :indent="25"
                    @node-click="nodeClick" node-key="id" :filter-node-method="filterNode" default-expand-all
                    highlight-current :default-expanded-keys="default_expanded_keys">
                    <div slot="reference" class="node-label" slot-scope="{ node, data }">
                        <label class="left" :title="node.label">
                            {{ node.label }}
                        </label>
                    </div>
                </el-tree>
                <sgUpload drag ref="sgUpload" :data="{
                    accept: `.${['chm'].join(',.')}`,
                    // actionUrl: `http://127.0.0.1:9999/api/chm/upload`,
                    actionUrl: `http://xxx.xxxxxx.cn:33/api/chm/upload`,
                    headers: {},
                }" @beforeUpload="beforeUpload" @uploadSuccess="uploadSuccess" @error="uploadError" hideUploadTray />
            </div>
        </div>
        <div class="sg-right ">
            <iframe id="iframe" ref="iframe" :src="src" frameborder="no" style="width:100%;height:100%;"></iframe>
        </div>
        <div class="hhcHTML" ref="hhcHTML" style="display: none;"> </div>
    </div>
</template>
<script>
import sgUpload from "@/vue/components/admin/sgUpload";
export default {
    name: 'chmDecode',
    components: {
        sgUpload,
    },
    data() {
        return {
            loading: false,
            htmPath: '',
            src: '',
            current_node: null,
            default_expanded_keys: [],
            treeData: [],
        }
    },
    created() {
    },
    methods: {
        // 解析hhc文件
        decodeHhcData(doms) {
            let r = [];
            let _recursion = (doms, d) => {
                [].slice.call(doms).forEach(v => {
                    let OBJECT = v.querySelector(`OBJECT`);
                    let p0 = OBJECT.querySelectorAll(`param`)[0];
                    let p1 = OBJECT.querySelectorAll(`param`)[1];
                    let obj = {
                        id: this.$g.UUID(),
                        [p0.getAttribute('name')]: p0.getAttribute('value'),//文件别名
                        [p1.getAttribute('name')]: p1.getAttribute('value'),
                        filePath: `${this.htmPath}${p1.getAttribute('value')}`,//文件路径
                    }
                    this.current_node || (this.current_node = obj);
                    d.push(obj)
                    if (OBJECT.nextElementSibling) {
                        obj.children = []
                        _recursion(OBJECT.nextElementSibling.children, obj.children)
                    }
                });
            }
            _recursion(doms, r);
            return r;
        },
        // 开始上传
        beforeUpload(d) {
            this.loading = true;
        },
        // 上传成功
        uploadSuccess(d, f) {
            this.htmPath = d.data.htmPath;
            this.$refs.hhcHTML.innerHTML = d.data.hhcData;
            this.$nextTick(() => {
                let treeData = this.decodeHhcData(this.$refs.hhcHTML.querySelectorAll(`.hhcHTML>ul>li`))
                this.treeData = treeData;
                this.loading = false;
                this.$nextTick(() => {
                    this.$refs.tree.setCurrentKey(this.current_node.id)
                    this.src = this.current_node.filePath;
                });
            });
        },
        // 上传失败
        uploadError(d, f) { this.loading = false; },
        //点击节点
        nodeClick(data) { },
        //过滤节点
        filterNode(value, data) { },
        // 树节点修改
        current_change(d) { this.src = d.filePath; },
    }
};
</script>
<style lang="scss" scoped>
.chmDecode {
    width: 100%;
    display: flex;
    flex-wrap: nowrap;
    $treeWidth: 610px;
    $treeControlWidth: 100px;
    &>.sg-left {
        width: $treeWidth;
        flex-wrap: nowrap;
        white-space: nowrap;
        flex-shrink: 0;
        .tree-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            &>.sg-left {}
            &>.sg-right {}
        }
        .tree-body {
            height: calc(100vh - 200px);
        }
    }
    &>.sg-right {
        margin-left: 20px;
        flex-grow: 1;
        height: calc(100vh - 170px);
        .baseinfo {
            width: 100%;
            height: 100%;
            overflow-x: hidden;
            overflow-y: auto;
            position: relative;
            .form-body {
                height: calc(100% - 60px);
                overflow-y: auto;
                overflow-x: hidden;
            }
            .form-footer {
                position: absolute;
                height: 70px;
                box-sizing: border-box;
                padding-top: 20px;
                width: 100%;
                display: flex;
                justify-content: space-between;
                bottom: 0;
                &>* {
                    width: 100%;
                    flex-grow: 1;
                }
            }
        }
    }
}
</style>


相关文章
|
10月前
|
存储 JSON API
如何将 Swagger 文档导出为 PDF 文件
你会发现自己可能需要将 Swagger 文档导出为 PDF 或文件,以便于共享和存档。在这篇博文中,我们将指导你完成将 Swagger 文档导出为 PDF 格式的过程。
|
7月前
|
C#
【PDF提取内容改名】批量提取PDF指定区域内容重命名PDF文件,PDF自动提取内容命名的方案和详细步骤
本工具可批量提取PDF中的合同编号、日期、发票号等关键信息,支持PDF自定义区域提取并自动重命名文件,适用于合同管理、发票处理、文档归档和数据录入场景。基于iTextSharp库实现,提供完整代码示例与百度、腾讯网盘下载链接,助力高效处理PDF文档。
899 40
|
7月前
|
编译器 Python
如何利用Python批量重命名PDF文件
本文介绍了如何使用Python提取PDF内容并用于文件重命名。通过安装Python环境、PyCharm编译器及Jupyter Notebook,结合tabula库实现PDF数据读取与处理,并提供代码示例与参考文献。
|
9月前
|
人工智能 算法 安全
使用CodeBuddy实现批量转换PPT、Excel、Word为PDF文件工具
通过 CodeBuddy 实现本地批量转换工具,让复杂的文档处理需求转化为 “需求描述→代码生成→一键运行” 的极简流程,真正实现 “技术为效率服务” 的目标。感兴趣的快来体验下把
496 10
|
8月前
|
数据采集 存储 API
Python爬虫结合API接口批量获取PDF文件
Python爬虫结合API接口批量获取PDF文件
|
监控 Java 应用服务中间件
高级java面试---spring.factories文件的解析源码API机制
【11月更文挑战第20天】Spring Boot是一个用于快速构建基于Spring框架的应用程序的开源框架。它通过自动配置、起步依赖和内嵌服务器等特性,极大地简化了Spring应用的开发和部署过程。本文将深入探讨Spring Boot的背景历史、业务场景、功能点以及底层原理,并通过Java代码手写模拟Spring Boot的启动过程,特别是spring.factories文件的解析源码API机制。
424 2
|
11月前
|
算法 测试技术 C语言
深入理解HTTP/2:nghttp2库源码解析及客户端实现示例
通过解析nghttp2库的源码和实现一个简单的HTTP/2客户端示例,本文详细介绍了HTTP/2的关键特性和nghttp2的核心实现。了解这些内容可以帮助开发者更好地理解HTTP/2协议,提高Web应用的性能和用户体验。对于实际开发中的应用,可以根据需要进一步优化和扩展代码,以满足具体需求。
1066 29
|
11月前
|
前端开发 数据安全/隐私保护 CDN
二次元聚合短视频解析去水印系统源码
二次元聚合短视频解析去水印系统源码
455 4
|
11月前
|
JavaScript 算法 前端开发
JS数组操作方法全景图,全网最全构建完整知识网络!js数组操作方法全集(实现筛选转换、随机排序洗牌算法、复杂数据处理统计等情景详解,附大量源码和易错点解析)
这些方法提供了对数组的全面操作,包括搜索、遍历、转换和聚合等。通过分为原地操作方法、非原地操作方法和其他方法便于您理解和记忆,并熟悉他们各自的使用方法与使用范围。详细的案例与进阶使用,方便您理解数组操作的底层原理。链式调用的几个案例,让您玩转数组操作。 只有锻炼思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
|
11月前
|
移动开发 前端开发 JavaScript
从入门到精通:H5游戏源码开发技术全解析与未来趋势洞察
H5游戏凭借其跨平台、易传播和开发成本低的优势,近年来发展迅猛。接下来,让我们深入了解 H5 游戏源码开发的技术教程以及未来的发展趋势。

热门文章

最新文章

推荐镜像

更多
  • DNS