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>


相关文章
|
JavaScript API
深入探索fs.WriteStream:Node.js文件写入流的全面解析
深入探索fs.WriteStream:Node.js文件写入流的全面解析
|
5月前
|
API PHP 索引
这插件太危险了!PDFParser自动扒取PDF每天躺赚300+的暴利搬运术
本文介绍了如何使用PHP提取PDF文档中的文字内容。为解决PDF文档“不可编辑”或“文本无法复制”的问题,推荐使用免费的PHP库——PDFParser。通过Composer安装后,可利用其简单强大的API解析PDF文件,提取文本内容。文章详细演示了获取PDF基本信息、全文内容、指定页内容及循环输出每页文本的方法,并附带中英文PDF示例,操作简便实用。
168 3
这插件太危险了!PDFParser自动扒取PDF每天躺赚300+的暴利搬运术
|
6月前
|
JavaScript 前端开发 UED
PDF在线预览实现:如何使用vue-pdf-embed实现前端PDF在线阅读
本文详细介绍了如何在Vue项目中使用vue-pdf-embed实现PDF文件的在线展示。从项目初始化、插件集成到高级功能的实现和部署优化,希望对你有所帮助。在实际项目中,灵活运用这些技术可以大大提升用户体验和项目质量。 只有锻炼思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
|
6月前
|
索引
【Flutter 开发必备】AzListView 组件全解析,打造丝滑索引列表!
在 Flutter 开发中,AzListView 是实现字母索引分类列表的理想选择。它支持 A-Z 快速跳转、悬浮分组标题、自定义 UI 和高效性能,适用于通讯录、城市选择等场景。本文将详细解析 AzListView 的核心参数和实战示例,助你轻松实现流畅的索引列表。
226 7
|
8月前
|
JSON 前端开发 搜索推荐
关于商品详情 API 接口 JSON 格式返回数据解析的示例
本文介绍商品详情API接口返回的JSON数据解析。最外层为`product`对象,包含商品基本信息(如id、name、price)、分类信息(category)、图片(images)、属性(attributes)、用户评价(reviews)、库存(stock)和卖家信息(seller)。每个字段详细描述了商品的不同方面,帮助开发者准确提取和展示数据。具体结构和字段含义需结合实际业务需求和API文档理解。
|
9月前
|
人工智能 搜索推荐 API
Cobalt:开源的流媒体下载工具,支持解析和下载全平台的视频、音频和图片,支持多种视频质量和格式,自动提取视频字幕
cobalt 是一款开源的流媒体下载工具,支持全平台视频、音频和图片下载,提供纯净、简洁无广告的体验
1345 9
Cobalt:开源的流媒体下载工具,支持解析和下载全平台的视频、音频和图片,支持多种视频质量和格式,自动提取视频字幕
|
9月前
|
JavaScript
jquery图片和pdf文件预览插件
EZView.js是一款jquery图片和pdf文件预览插件。EZView.js可以为图片和pdf格式文件生成在线预览效果。支持的文件格式有pdf、jpg、 png、jpeg、gif。
263 16
|
11月前
|
存储 编译器 数据安全/隐私保护
【C++篇】C++类与对象深度解析(四):初始化列表、类型转换与static成员详解2
【C++篇】C++类与对象深度解析(四):初始化列表、类型转换与static成员详解
142 3
|
11月前
|
编译器 C++
【C++篇】C++类与对象深度解析(四):初始化列表、类型转换与static成员详解1
【C++篇】C++类与对象深度解析(四):初始化列表、类型转换与static成员详解
222 3
|
移动开发 资源调度 JavaScript
Vue移动端网页(H5)预览pdf文件(pdfh5和vue-pdf)
这篇文章介绍了在Vue移动端网页中使用`pdfh5`和`vue-pdf`两个插件来实现PDF文件的预览,包括滚动查看、缩放、添加水印、分页加载、跳转指定页数等功能。
8046 1
Vue移动端网页(H5)预览pdf文件(pdfh5和vue-pdf)

推荐镜像

更多
  • DNS