Last active
April 30, 2020 15:12
-
-
Save gera2ld/560e7314dd9cdefd110bd019d8603353 to your computer and use it in GitHub Desktop.
tar extract from buffer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { Readable } = require('stream'); | |
const tar = require('tar'); | |
export function string2stream(stringOrBuffer) { | |
const reader = new Readable(); | |
reader.push(stringOrBuffer); | |
reader.push(null); | |
return reader; | |
} | |
function readEntry(entry) { | |
return new Promise((resolve, reject) => { | |
const buffers = []; | |
entry.on('data', c => { | |
buffers.push(c); | |
}); | |
entry.on('end', err => { | |
if (err) reject(err); | |
else resolve([entry.path, Buffer.concat(buffers)]); | |
}); | |
}); | |
} | |
async function readEntries(promises) { | |
const entries = await Promise.all(promises); | |
return entries.reduce((res, [path, buffer]) => { | |
res[path] = buffer; | |
return res; | |
}, {}); | |
} | |
function extractFromTarBuffer(buffer) { | |
return new Promise((resolve, reject) => { | |
const promises = []; | |
string2stream(buffer) | |
.pipe(tar.t({ | |
onentry(entry) { | |
promises.push(readEntry(entry)); | |
}, | |
})) | |
.on('end', err => { | |
if (err) reject(err); | |
else resolve(readEntries(promises)); | |
}); | |
}); | |
} | |
(async () => { | |
console.log(await extractFromTarBuffer(await require('fs').promises.readFile('foo.tar'))); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment