3

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?

Pavel Fedotov
  • 748
  • 1
  • 7
  • 29
haleonj
  • 1,438
  • 3
  • 16
  • 30

3 Answers3

2

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

Gilson Cavalcanti
  • 1,483
  • 1
  • 12
  • 18
  • 1
    That's useful documentation, but I cannot put the code in an async function like that in a straightforward way because of the second error I mentioned: If I call such a function twice I get an error from Unhandled Rejection (LockExistsError): Lock already being held for file: ipfs/repo.lock. – haleonj Mar 23 '21 at 11:38
1

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
}
Peter
  • 656
  • 1
  • 6
  • 14
1

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 a very rough patch in this case:

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

Pavel Fedotov
  • 748
  • 1
  • 7
  • 29