Ander Acosta
Ander Acosta

Reputation: 1069

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)
        }
    })
})

Upvotes: 3

Views: 5240

Answers (2)

Mandeep Singh
Mandeep Singh

Reputation: 51

From nodejs you can do something like this provided necessary packages are imported:

const fileHash = 'you hash of the file you want to get'

ipfs.files.get(fileHash, function (err, files) {
    files.forEach((file) => {
        console.log(file.path)
        console.log("File content >> ",file.content.toString('utf8'))
    })
})

Upvotes: 2

ufxmeng
ufxmeng

Reputation: 2600

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

Upvotes: 4

Related Questions