从 Node.js 中的 .rar 文件中读取所有文件名

Read All File Names from a .rar File in Node.js

我有一条快速路线,可以上传文件,这些文件通过 formData 发送到服务器。

假设该文件是一个 .rar 文件,我的目标是提取该存档或其子文件夹中的所有文件名。

这是我的快速路线目前的样子:

module.exports = async (req, res) => {
    try {
        const busboy = new Busboy({ headers: req.headers })
        busboy.on('finish', async () => {
            const fileData = req.files.file
            console.log(fileData)
            // upload file
            // send back response
        })
        req.pipe(busboy)
    } catch (err) { return response.error(req, res, err, 'uploadProductFile_unexpected') }
}

这是 console.log(fileData) 的样子:

{
    data:
        <Buffer 52 61 72 21 1a 07 01 00 56 0c 22 93 0c 01 05 08 00 07 01 01 8d d6 8d 80 00 85 76 33 e4 49 02 03 0b fc d4 0d 04 b1 8c 1e 20 bc 86 da 2e 80 13
    00 2b 66 ... >,
    name: 'filename.rar',
    encoding: '7bit',
    mimetype: 'application/octet-stream',
    truncated: false,
    size: 224136
}

filename.rar 中有一些文件,例如 texture.pnginfo.txt。我的目标是获取这些名称。

使用:npm i node-rar

const rar = require('node-rar')

rar.list('path/to/file.rar', 'optional password')

参考:https://www.npmjs.com/package/node-rar

您可以使用 decompress 接受 Buffer 作为参数:

const Busboy = require('busboy');
const decompress = require('decompress');

module.exports = async (req, res) => {
    try {
        const busboy = new Busboy({ headers: req.headers })
        busboy.on('finish', async () => {
            const fileData = req.files.file
            console.log(fileData)
            // upload file
            // send back response

            decompress(fileData, 'dist').then(files => {
                req.send(files.map(f => f.path))
            });
        })
        req.pipe(busboy)
    } catch (err) { return response.error(req, res, err, 'uploadProductFile_unexpected') }
}

我最终找到了使用 node-unrar-js 的解决方案:

const unrar = require('node-unrar-js')

module.exports = async (req, res) => {
    try {
        const busboy = new Busboy({ headers: req.headers })
        busboy.on('finish', async () => {

            const fileData = req.files.file
            const extractor = unrar.createExtractorFromData(fileData.data)
            const list = extractor.getFileList()
            if (list[0].state === 'SUCCESS')
                //  Here I have the file names
                const fileNmes = list[1].fileHeaders.map(header => header.name)
                // ...

        })
        req.pipe(busboy)
    } catch (err) { return response.error(req, res, err, 'uploadProductFile_unexpected') }
}

步骤可以是:

npm install -g node-rar

npm install node-rar

node-rar --version

在您的文件中:

var rar = require('node-rar');

/// list archive entries
rar.list('path/to/file.rar', 'optional password');
// => [entries]

/// test archive entries
rar.test('path/to/file.rar', 'dir/to/test', 'optional password');
// => [entries]

/// extract archive entries
rar.extract('path/to/file.rar', 'dir/to/extract', 'optional password');
// => [entries]