Search code examples
javascriptnode.jsipfs

How download file via ipfs using Nodejs?


I am trying to implement IPFS in an application made with NodeJS. I can add file and get the CID, but if I try to download it with ipfs get <CID> it does not download anything. Any ideas what can be ?. I use this code to start an IPFS node:

const IPFS = require('ipfs');
// Spawn your IPFS node \o/
const node = new IPFS();

node.on('ready', () => {
    node.id((err, id) => {
        if (err) {
            return console.log(err)
        }
        console.log(id)
    })

    let files = [
        {
            path: '/home/my/file.jpg',
            content: File.read('/home/my/file.jpg', null)
        }
    ]
    node.files.add(files, function (err, files) {
        if (err) {
            console.log(err);
        } else {
            console.log(files)
        }
    })
})

Solution

  • When you start the node application, you will get some output like this:

    [ { path: 'home/my/Pictures',
        hash: '...hash',
        size: 10329 },
      { path: 'home/my',
        hash: '...hash',
        size: 10384 },
      { path: 'home',
        hash: '...hash',
        size: 10435 },
      { path: '/home/my/Pictures/google.png',
        hash: 'QmYeznhKxbZY37g5ymFzWnmrbP8ph2fdxycAuw9S9goUYr',
        size: 10272 } ]
    

    then copy that file hash, make sure you can access that file from the browser.

    // replace the hash code for your own need
    https://ipfs.io/ipfs/QmYeznhKxbZY37g5ymFzWnmrbP8ph2fdxycAuw9S9goUYr
    

    then download the file in your terminal

    // replace the hash code for your own need
    ipfs get QmYeznhKxbZY37g5ymFzWnmrbP8ph2fdxycAuw9S9goUYr -o=google.png
    

    Check here for more options