[Ethereum] How to implement buffer/readable stream in order to add a file to IPFS

ipfsjavascript

I'm trying to upload a file from my directory to IPFS.

Below is what they require from API:

const files = [
  {
    path: '/tmp/myfile.txt',
    content: (Buffer or Readable stream)
  }
]

ipfs.files.add(files, function (err, files) {
  // 'files' will be an array of objects containing paths and the multihashes of the files added
})

I don't understand what they mean by "Buffer or Readable stream." More specifically, I'm not sure how to implement it correctly because I haven't done it before.

What is the difference between "path" and "content"? Why do they need to be separated?

Source: https://github.com/ipfs/js-ipfs/tree/master/examples/ipfs-101

Best Answer

js-ipfs expect you to read the file into a Buffer (an array with data). Did you happen to find docs on https://github.com/ipfs/interface-ipfs-core/blob/master/SPEC/FILES.md#files-api.

You can see how to create a buffer right in the example https://github.com/ipfs/js-ipfs/blob/master/examples/ipfs-101/1.js#L18 or learn how to read a file into a Buffer in the Node.js documentation https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options

Hope this helps :)

Update: Here is a way to do it

const fs = require('fs')
const files = [
  {
    path: '/tmp/myfile.txt',
    content: fs.readFileSync('/tmp/myfile.txt')
  }
]

ipfs.files.add(files, function (err, files) {
  // 'files' will be an array of objects containing paths and the multihashes of the files added
})
Related Topic