Unexpected token p in JSON at position 0

Hi Team,

I am trying to use ipfs-api to upload local files to ipfs network via nodejs app.

However, it is failing at ipfs.add function with following error :slightly_frowning_face:

<Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 0f a0 00 00 08 ca 08 06 00 00 00 82 b7 f1 b0 00 00 00 09 70 48 59 73 00 00 2e 23 00 00 2e 23 01 ... 109107 more bytes>
error inside ipfs.add function SyntaxError: Unexpected token p in JSON at position 0
    at JSON.parse (<anonymous>)
    at /Users/shubham/DIP/node_modules/ipfs-api/src/utils/stream-to-json-value.js:25:18
    at /Users/shubham/DIP/node_modules/ipfs-api/src/utils/stream-to-value.js:12:22
    at ConcatStream.<anonymous> (/Users/shubham/DIP/node_modules/concat-stream/index.js:37:43)
    at ConcatStream.emit (node:events:539:35)
    at finishMaybe (/Users/shubham/DIP/node_modules/readable-stream/lib/_stream_writable.js:630:14)
    at afterWrite (/Users/shubham/DIP/node_modules/readable-stream/lib/_stream_writable.js:492:3)
    at processTicksAndRejections (node:internal/process/task_queues:85:21)

Here is the sample code used for the same →

const ipfsAPI = require('ipfs-api');
const fs = require('fs');

//Connceting to the ipfs network via infura gateway
const ipfs = new ipfsAPI({ host: 'ipfs.infura.io', port: 5001, protocol: 'https' })

//Addfile router for adding file a local file to the IPFS network without any local node

const uploadToIpfs = async() => {
    
    console.log(ipfs)
    //Reading file from computer
    let testFile = fs.readFileSync("./helpers/1.png");
    
    let testBuffer = await Buffer.from(testFile);

    console.log(testBuffer);
   
    const result = await ipfs.files.add(testBuffer, (error, result) => {
        if (error) {
          console.error("error inside ipfs.add function", error);
        } else {
          // The image data has been successfully added to IPFS
          console.log(result[0].hash); // Print the IPFS hash of the image
        }
      });
    return result;
}

I’m not sure which library you’re using as ipfs.files.add I don’t believe is part of the CoreAPI, instead I’d try ipfs.add.