Search code examples
javascriptnode.jsarchiverarwinrar

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


I have an express route, that uploads files, that are sent to the server via formData.

Supposing the file is a .rar file, my goal is to extract all file names, that are inside this archive or it's subfolders.

This is how my express route currently looks like:

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') }
}

Here is what the console.log(fileData) looks like:

{
    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
}

Inside filename.rar are a few files like texture.png and info.txt. And my goal is to fetch those names.


Solution

  • I eventually found an solution using 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') }
    }