construct-js
construct-js 介绍
construct-js是一个用于创建字节级数据结构的库。它侧重于声明性API和使用简单性。
安装@H_502_6@
npm i construct-js
示例 @H_502_6@
以下示例构建一个完全有效的zip存档,其中包含一个文件 - helloworld.txt。
const fs = require('fs');
const {
RawString,
U16,
U32,
Struct,
} = require('construct-js');
const data = RawString('helloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworld');
const filename = RawString('helloworld.txt');
const sharedHeaderInfo = Struct('sharedHeaderInfo')
.field('minVersion',U16(10))
.field('gpFlag',U16(0))
.field('compressionMethod',U16(0))
.field('lastModifiedTime',U16(0))
.field('lastModifiedDate',U16(0))
.field('crc32',U32(0))
.field('compressedSized',U32(data.byteLength))
.field('uncompressedSized',U32(data.byteLength))
.field('filenameSize',U16(filename.byteLength))
.field('extraFieldLength',U16(0));
const localHeader = Struct('localHeader')
.field('header',U32(0x04034b50))
.field('sharedHeaderInfo',sharedHeaderInfo)
.field('filename',filename);
const centralDirectory = Struct('centralDirectory')
.field('header',U32(0x02014b50))
.field('madeByVersion',U16(10))
.field('sharedHeaderInfo',sharedHeaderInfo)
.field('fileCommentSize',U16(0))
.field('diskNumber',U16(0))
.field('internalFileAttributes',U16(0))
.field('externalFileAttributes',U32(0))
.field('relativeOffset',U32(0))
.field('filename',filename);
const endOfCentralDirectory = Struct('endOfCentralDirectory')
.field('header',U32(0x06054b50))
.field('diskNumber',U16(0))
.field('centralDirdiskStart',U16(0))
.field('numberOfCentralDirsOndisk',U16(1))
.field('totalNumberOfCentralDirs',U16(1))
.field('centralDirsize',U32(0))
.field('offsetToStart',U32(0))
.field('commentLength',U16(0));
const zipFile = Struct('ZipFile')
.field('localHeader',localHeader)
.field('data',data)
.field('centralDirectory',centralDirectory)
.field('endOfCentralDirectory',endOfCentralDirectory);
const offset = zipFile.getoffset('centralDirectory');
endOfCentralDirectory.get('offsetToStart').set(offset);
const filebuffer = zipFile.toBuffer();
fs.writeFile('./test.zip',filebuffer,() => {});
GitHub:@H_502_6@https://github.com/francisrstokes/construct-js
网站描述:@H_502_6@一个用于创建字节级别数据结构的库