首页 > 解决方案 > 如何将文件转换为 .RAR 文件节点 js

问题描述

在我的项目中,我有一个项目表。每个项目都有一个下载 pdf 文件的栏目。现在我希望能够下载所有文件并创建一个 .rar 文件。有一个下载单个文件的代码:

路由.js

app.get('/api/download/archive/:filename', function(req,res){
    res.download("public/uploads/"+req.params.filename, req.params.filename);
}) 

归档.js

$scope.downloadPdf = function(obj){
    $http.get('api/download/archive/'+obj.Documentation)
    .success(function(data){
        window.open('api/download/archive/'+obj.Documentation)
    });
}

标签: angularjsnode.jsrar

解决方案


不幸的是,RAR 是一个闭源软件。因此,创建存档的唯一方法是安装名为的命令行实用程序rar,然后rar a在子进程中使用命令来压缩文件。

rar在 Mac 上安装,我必须运行brew install homebrew/cask/rar. 您可以在此处找到其他平台的安装说明。

安装后可以child_process这样使用:

const { exec } = require('child_process');
const { promisify } = require('util');
const fs = require('fs');
const path = require('path');

// Promisify `unlink` and `exec` functions as by default they accept callbacks
const unlinkAsync = promisify(fs.unlink);
const execAsync = promisify(exec);

(async () => {
    // Generating a different name each time to avoid any possible collisions
    const archiveFileName = `temp-archive-${(new Date()).getTime()}.rar`;
    // The files that are going to be compressed.
    const filePattern = `*.jpg`;

    // Using a `rar` utility in a separate process
    await execAsync(`rar a ${archiveFileName} ${filePattern}`);

    // If no error thrown the archive has been created
    console.log('Archive has been successfully created');

    // Now we can allow downloading it

    // Delete the archive when it's not needed anymore
    // await unlinkAsync(path.join(__dirname, archiveFileName));

    console.log('Deleted an archive');
})();

为了运行示例,请将一些.jpg文件放入项目目录中。

PS:如果您选择不同的存档格式(例如 .zip),您将能够使用例如存档器之类的东西。这可能允许您创建一个 zip 流并将其通过管道直接响应。因此,您无需在磁盘上创建任何文件。但这是一个不同的问题。


推荐阅读