construct-js 介绍
construct-js是一个用于创建字节级数据结构的库。它侧重于声明性API和使用简单性。
安装
npm i construct-js
示例
以下示例构建一个完全有效的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:https://github.com/francisrstokes/construct-js
网站描述:一个用于创建字节级别数据结构的库
construct-js
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。