node-unrar-js
Version:
Pure JavaScript RAR archive extractor by compile the official unrar lib by Emscripten.
77 lines • 2.38 kB
JavaScript
import * as fs from 'fs';
import * as path from 'path';
import { Extractor } from './Extractor';
export class ExtractorFile extends Extractor {
constructor(
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types,@typescript-eslint/no-explicit-any
unrar, filepath, targetPath, password, filenameTransform) {
super(unrar, password);
this.filenameTransform = filenameTransform;
this._filePath = filepath;
this.fileMap = {};
this._target = targetPath;
}
open(filename) {
const fd = fs.openSync(filename, 'r');
this.fileMap[fd] = {
size: fs.fstatSync(fd).size,
pos: 0,
name: filename,
};
return fd;
}
create(filename) {
const fullpath = path.join(this._target, this.filenameTransform(filename));
const dir = path.parse(fullpath).dir;
// Skip if directory is the current directory
if (dir !== '') {
fs.mkdirSync(dir, { recursive: true });
}
const fd = fs.openSync(fullpath, 'w');
this.fileMap[fd] = {
size: 0,
pos: 0,
name: filename,
};
return fd;
}
closeFile(fd) {
delete this.fileMap[fd];
fs.closeSync(fd);
}
read(fd, buf, size) {
const file = this.fileMap[fd];
const buffer = Buffer.allocUnsafe(size);
const readed = fs.readSync(fd, buffer, 0, size, file.pos);
this.unrar.HEAPU8.set(buffer, buf);
file.pos += readed;
return readed;
}
write(fd, buf, size) {
const file = this.fileMap[fd];
const writeNum = fs.writeSync(fd, Buffer.from(this.unrar.HEAPU8.subarray(buf, buf + size)), 0, size);
file.pos += writeNum;
file.size += writeNum;
return writeNum === size;
}
tell(fd) {
return this.fileMap[fd].pos;
}
seek(fd, pos, method) {
const file = this.fileMap[fd];
let newPos = file.pos;
if (method === 'SET') {
newPos = 0;
}
else if (method === 'END') {
newPos = file.size;
}
newPos += pos;
if (newPos < 0 || newPos > file.size) {
return false;
}
file.pos = newPos;
return true;
}
}
//# sourceMappingURL=ExtractorFile.js.map