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

Now I try it but i got error

const ipfsClient = require('ipfs-http-client');

const projectId = '### i put my infura idkey ';
const projectSecret = '###i put my infura secretkey';

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

my node version v16.16.0

Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main defined in C:\Users\user\Desktop\JQDapp\dappweb\node_modules\ipfs-http-client\package.json
   at throwExportsNotFound (node:internal/modules/esm/resolve:472:9)
   at packageExportsResolve (node:internal/modules/esm/resolve:693:7)
   at resolveExports (node:internal/modules/cjs/loader:482:36)
   at Function.Module._findPath (node:internal/modules/cjs/loader:522:31)
   at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
   at Function.Module._load (node:internal/modules/cjs/loader:778:27)
   at Module.require (node:internal/modules/cjs/loader:1005:19)
   at require (node:internal/modules/cjs/helpers:102:18)
   at Object.<anonymous> (C:\Users\user\Desktop\JQDapp\dappweb\index.js:2:20) {
 code: 'ERR_PACKAGE_PATH_NOT_EXPORTED'
}

Could you try updating your node and reinstalling node modules in your project folder?

I have try same but i got same error again.
Can you please tell me how we can solve the error of this type…

hi @Flaviu ,

i tried the same process but i get the error below

ERROR: No “exports” main defined in C:\Users\DELL\multi\node_modules\ipfs-http-client\package.json

Import ipfs-http-client like this. I had the same issue.

async function ipfsClient() {
    const { create } = await import('ipfs-http-client')
    const client= await create(
        {
            host: "ipfs.infura.io",
            port: 5001,
            protocol: "https",
            headers: {
                "Authorization": `Basic ${Buffer.from(projectIdAndSecret).toString("base64")}`
        }
    });
    return client;
}
1 Like

Hey all,

If you are running into “no exports defined” errors and using this import method:

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

Please install this ipfs-http-client package instead with:
npm install ipfs-http-client@50.1.2


If you are installing the latest version of ipfs-http-client (57.0.3) with just npm install ipfs-http-client
There are some slight changes on how it is imported referenced here: ipfs-http-client - npm

Please import the latest version of ipfs-http-client using { create } as @kaweendras pointed out.

async function ipfsClient() {
    const { create } = await import('ipfs-http-client')
    const client= await create(
        {
            host: "ipfs.infura.io",
            port: 5001,
            protocol: "https",
            headers: {
                "Authorization": `Basic ${Buffer.from(projectIdAndSecret).toString("base64")}`
        }
    });

Thanks @kaweendras !

Kind regards,
Alex | Infura Support | Consensys

1 Like

Hello, I´ve installed npm install ipfs-http-client@50.1.2 package but when I attempted to run the command import('ipfs-http-client'); under Truffle console it still gives me the following error message:

truffle(mainnet_fork)> import(‘ipfs-http-client’);
Uncaught TypeError: A dynamic import callback was not specified.

  • at importModuleDynamicallyCallback (node:internal/process/esm_loader:39:9)*
  • at new NodeError (node:internal/errors:387:5)*
  • at __node_internal_captureLargerStackTrace (node:internal/errors:477:5) {*
  • code: ‘ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING’*
    }

Would greatly appreciate your help as it´s driving me bonkers!

Thank you

Please try the 57.0.3 ipfs-http-client module and let me know if you still have that import error.

Thank you