huan/file-box

New feature: FileBox.fromJSON() & fileBox.toJSON()

huan opened this issue · 0 comments

huan commented

After enabling serialization for FileBox, we can transfer the FileBox on the wire.

Talk is cheap, show me the code

const fileBox = FileBox.fromQRCode('https://github.com')

const jsonText = JSON.stringify(fileBox)
// the above code equals to the following line of code:
// const jsonText = fileBox.toJSON()

// we will get the serialized data for this FileBox:
console.log(jsonText)

// restore our fleBox:
const newFileBox = FileBox.fromJSON(jsonText)

Limitation

Because we want to enable the JSON.stringify(fileBox), which will call fileBox.toJSON(), so the toJSON() can not be async, which means we can only support limited FileBoxType(s):

  1. FileBoxType.Base64
  2. FileBoxType.Url
  3. FileBoxType.QRCode

For other types like FileBoxType.Flie, FileBoxType.Buffer, FileBoxType.Stream, etc, we need to transform them to FileBoxType.Base64 before we call toJSON:

const fileBoxBefore = FileBox.fromFile('./test.txt')
const base64 = await fileBoxBefore.toBase64()

const fileBoxAfter = FleBox.fromBase64(base64, 'test.txt')
// fileBoxAfter will be serializable

console.log(JSON.stringify(fileBoxAfter))