Import ipfs in TypeScript

Viewed 1156

Importing and module initialization is generally simple using JavaScript/TypeScript using either require or import. I'm having trouble running the basic example from the JS IPFS website to initialize ipfs.

If I follow the general instructions I get an error: Module parse failed: Cannot use keyword 'await' outside an async function (6:13)

This is the critical code:

const IPFS = require('ipfs-core');
const ipfs = await IPFS.create();

If I follow the suggestion to place the ipfs creation in an async function I just delay the inevitable. If I call such a function twice I get an error from Unhandled Rejection (LockExistsError): Lock already being held for file: ipfs/repo.lock. It seems I could create a hack to test whether ipfs is created or not and initialize it global to a module as null, but that would still be a hack.

How should I implement or refactor const ipfs = await IPFS.create(); without error?

3 Answers

Probably your Node version is prior to version 14 and don't support calling await in the top-level. You got be in the context of an async block. You can do something like:

const IPFS = require('ipfs')

async function main() {
  const ipfs = await IPFS.create()
  /* Your code here */
}

// and now you can tell node to run your async main function...
main()

Check https://v8.dev/features/top-level-await for more info about it in the v8 engine. And also found this post about the Node 14 support for it: https://pprathameshmore.medium.com/top-level-await-support-in-node-js-v14-3-0-8af4f4a4d478

In my case, it was due to me initializing IFPS unnecessarily too many times in a row. After making sure the IPFS instance is only initialized once when my app starts, I was able to resolve the error.

let ready = false
if(!ready) {
  const ipfs = await IPFS.create()
  ready = true
}

In my case the user input goes to ipfs and on additional upload the error "ipfs/repo.lock" continued to come up. After some research on ipfs wiki, it appears that there are conflicts with how ipfs actually works. Randomization of repo name is rough patch in this case:

const node = await IPFS.create({ repo: "ok" + Math.random() });

Related