-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
70 lines (65 loc) · 2.37 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
const powfile = require('powfile')
const fs = require('fs-extra')
const path = require('path')
const commondir = require('commondir')
const mime = require('mime/lite')
const glob = require('glob-promise')
const { parseResponse } = require('parse-raw-http').parseResponse
const create = async ({ image, files }) => {
console.log('creating...')
const imageData = await fs.readFile(image)
const commonParentDir = commondir(process.cwd(), files)
let parentPrefix = path.relative(process.cwd(), commonParentDir)
if (parentPrefix.length > 0) parentPrefix += path.sep
const fileMap = {}
// get *all* the files, recursively
let allFiles = files.slice(0)
await Promise.all(files.map(async f => {
const matches = await glob(`${f}/**`)
matches.forEach(m => {
if (!allFiles.includes(m)) allFiles.push(m)
})
}))
allFiles = allFiles.filter(f => !fs.lstatSync(f).isDirectory())
// if it's a single file, just pack it
if (allFiles.length === 1) {
const f = allFiles[0]
const data = await fs.readFile(f)
return powfile.create({ image: imageData, data, contentType: mime.getType(f) })
} else {
await Promise.all(allFiles.map(async f => {
console.log("reading", f)
const fileData = await fs.readFile(f)
fileMap[f.slice(parentPrefix.length)] = fileData
}))
return powfile.create({ image: imageData, files: fileMap })
}
}
const extract = async ({ image, dir='.', unzip=true }) => {
await fs.mkdirp(dir)
const imageData = await fs.readFile(image)
const extracted = await powfile.parse(imageData, { unzip })
if (extracted instanceof Buffer) {
const { headers, bodyData } = parseResponse(extracted, { decodeContentEncoding: true })
const ext = mime.getExtension(headers['content-type'])
const outputFilename = `index.${ext}`
console.log("extracting", outputFilename)
const outputPath = path.join(dir, outputFilename)
await fs.mkdirp(path.dirname(outputPath))
await fs.writeFile(outputPath, bodyData)
} else {
extracted.forEach(async filepath => {
if (!filepath.match(/\/$/)) {
console.log("extracting", filepath)
const outputPath = path.join(dir, filepath)
await fs.mkdirp(path.dirname(outputPath))
const data = await extracted.file(filepath).async("nodebuffer")
await fs.writeFile(outputPath, data)
}
})
}
}
module.exports = {
create,
extract
}