Add file to ipfs (node.js)

Hi frens,

sorry for my newby question but I want to add a string to ipfs and return the hash to console.
I cant find any example code for node.js in documentation.
I tried this but nothing happened (no console-log).

This is my code:

    const ipfsClient = require('ipfs-http-client');
const projectId = '1x..';
const projectSecret = '216a..';
// const ipfs = ipfsClient({ host: 'ipfs.infura.io', port: 5001, protocol: 'https' })

const auth =
  'Basic ' + Buffer.from(projectId + ':' + projectSecret).toString('base64')

const client = ipfsClient({
  host: 'ipfs.infura.io',
  port: 5001,
  protocol: 'https',
  apiPath: '/api/v0/',
  headers: {
    authorization: auth
  }
})

client.add("Hello", async(err, res) =>{
    console.log(res);
    if(err){
        console.log(err)
    }
    else {
        const hash = await res[0].hash;
        console.log(hash);
    }
});

Many thanks in advance,
Res

Hi Res,

Let me take a look and come back to you with a working solution.

Thanks for your patience.

Hi Flaviu,

thanks for your reply. Some weeks ago I was able to add an image (base64 encoded) as string buffer.
And return the hash as result.

var base64Image = s.split(';base64,').pop();
var buf = Buffer.from(base64Image, 'base64');
let result2 = client.add(buf);

Everything works fine. But now nothing happened.
I studied the new documentation and changed the code.

I followed this example code (Link):

client.pin.add('QmeGAVddnBSnKc1DLE7DLV9uuTqo5F7QbaveTjr45JUdQn').then((res) => {
console.log(res);
});

works fine but I dont have a hash value I need to return the hash.

I found this in another cummunity forum:
Note 1: The ipfs.add method is not only capable of uploading files into IPFS, but also data. Feel free to upload any random text to IPFS, such as await (ipfs as IPFSHTTPClient).add('Hello World') .

So how can I add random text and return the hash?

Thanks in advance
Res

Hi @creatorbox

Please use the following working code and let me know if you get the desired result.

const ipfsClient = require('ipfs-http-client');
const projectId = '23jSp...XXX;
const projectSecret = '23...XXX';
const auth =
    'Basic ' + Buffer.from(projectId + ':' + projectSecret).toString('base64');

const client = ipfsClient.create({
    host: 'ipfs.infura.io',
    port: 5001,
    protocol: 'https',
    headers: {
        authorization: auth,
    },
});

client.add('Hello World').then((res) => {
    console.log(res);
});

Hi @Flaviu

now I get this error message:

TypeError: client.add(…).then is not a function

Hi @creatorbox

Could you please let me know if you successfully installed ipfs-https-client using npm install --save ipfs-http-client?

Aaaannd finally it works!

I installed the library again with:
npm i --save-dev ipfs-http-client

Thanks a lot for your help!!^

Cheers

2 Likes