Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import ipfs in TypeScript

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?

like image 516
haleonj Avatar asked Apr 06 '26 21:04

haleonj


1 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

like image 199
Gilson Cavalcanti Avatar answered Apr 09 '26 11:04

Gilson Cavalcanti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!