How to unpack archives with Node.js and the 7-Zip CLI (using the “spawn()” method)?

22 hours ago 2
ARTICLE AD BOX

I need to complete the following task (with only two tools: Node.js and the 7-Zip CLI):

Read a directory recursively; For each file whose extension is .zip, unpack it with the 7-Zip CLI in the corresponding file's directory (I am interested in using the “spawn()” method to spawn a new process); When the 'close' event is emitted, log the corresponding exit code.

I used the following code:

import { readdir } from 'node:fs/promises'; import { join, extname } from 'node:path'; import { spawn } from 'node:child_process'; const pathToDir = 'D:\\test\\mydirectory'; try { const entries = await readdir(pathToDir, { recursive: true, withFileTypes: true }); for (const entry of entries) { const extension = extname(entry.name); if (extension === '.zip') { const extract = spawn( 'C:\\software\\7z2501-extra\\x64\\7za.exe', [ 'x', join(entry.parentPath, entry.name), '-o"' + entry.parentPath + '"' ] ); extract.on( 'close', ( code ) => console.log( `child process exited with code ${code}` ) ); } } } catch (err) { console.error(err); }

But it does not work: files are not unpacked, all I get is messages indicating that 7-Zip had an error. I tried to enclose the second argument in double quotes:

'"' + join(entry.parentPath, entry.name) + '"'

But the result is the same. Why? How to solve the problem?

Read Entire Article