保存到IPFS之前Buffer的使用
The use of Buffer before saving to IPFS
我正在关注 IPFS github example 以保存到 IPFS:
'use strict'
const IPFS = require('ipfs')
const all = require('it-all')
async function main () {
const node = await IPFS.create()
const version = await node.version()
console.log('Version:', version.version)
for await (const file of await node.add({
path: 'hello.txt',
content: Buffer.from('Hello World 101') //<<<=== why Buffer before assigned to content?
})) {
console.log('Added file:', file.path, file.cid.toString())
const data = Buffer.concat(await all(node.cat(file.cid)))
console.log('Added file contents:', data.toString())
}
}
main()
我注意到字符串在保存之前用 Buffer
转换为二进制。有人可以在这里解释 Buffer
的用法吗?保存图像或视频文件怎么样?
默认情况下 Node.js 与缓冲区一起工作,其中使用可以是流的 API,如果您在 JavaScript 中使用字符串,这些可以在 unicode (utf-8) 中工作,并且这些可以与二进制文件一起使用数据(例如,图像、视频文件等)。
一个区分字符串与缓冲区的简单示例可以是比较 UTF-8 字符串的大小,作为 unicode 文本(按字符计算)和缓冲区(按字节计算):
> const str = 'Hello 世界';
undefined
> str.length
8
> const buf = Buffer.from(str, 'utf8');
undefined
> buf.length
12
> buf.toString('hex');
'48656c6c6f7720e4b896e7958c'
> buf.toString('utf8');
'Hello 世界'
总而言之,它是使用 FS、Socket 等 API 缓冲区的标准工作
我正在关注 IPFS github example 以保存到 IPFS:
'use strict'
const IPFS = require('ipfs')
const all = require('it-all')
async function main () {
const node = await IPFS.create()
const version = await node.version()
console.log('Version:', version.version)
for await (const file of await node.add({
path: 'hello.txt',
content: Buffer.from('Hello World 101') //<<<=== why Buffer before assigned to content?
})) {
console.log('Added file:', file.path, file.cid.toString())
const data = Buffer.concat(await all(node.cat(file.cid)))
console.log('Added file contents:', data.toString())
}
}
main()
我注意到字符串在保存之前用 Buffer
转换为二进制。有人可以在这里解释 Buffer
的用法吗?保存图像或视频文件怎么样?
默认情况下 Node.js 与缓冲区一起工作,其中使用可以是流的 API,如果您在 JavaScript 中使用字符串,这些可以在 unicode (utf-8) 中工作,并且这些可以与二进制文件一起使用数据(例如,图像、视频文件等)。
一个区分字符串与缓冲区的简单示例可以是比较 UTF-8 字符串的大小,作为 unicode 文本(按字符计算)和缓冲区(按字节计算):
> const str = 'Hello 世界';
undefined
> str.length
8
> const buf = Buffer.from(str, 'utf8');
undefined
> buf.length
12
> buf.toString('hex');
'48656c6c6f7720e4b896e7958c'
> buf.toString('utf8');
'Hello 世界'
总而言之,它是使用 FS、Socket 等 API 缓冲区的标准工作