Close ipfs node js-ipfs

I have a react app that uses js-ipfs to add files to the network.

In the app there’s an ‘upload file’ page that starts a js-ipfs node when the component mounts like this:

startIPFS = async function (){

  •    const node = await window.Ipfs.create()*
  •    console.log('starting ipfs', node)*
  •    this.setState({node: node})*


  •  startIPFS()*


I can then use this.state.node to add files like this:

for await (const file of await this.state.node.add({

  •        path: someFileName,*
  •        content: Buffer.from(fileData, 'base64')*

*})) *

  •        console.log('Added file:', file.path, file.cid.toString()) *


The problem is if the user navigates away from the upload page and back to it later an error is thrown because the ipfs node has already been created: LockExistsError: Lock already being held for file: ipfs/repo.lock

Is there a way to close the node when a user navigates away from the page (ie when the component unmounts). I’m hoping for something like window.Ipfs.close()

Or is it better practice to start a node on the entire web app loading? so that way I’m not creating and closing the ipfs node every time a user lands on the ‘upload file’ page

I was able to figure it out.

as noted before I started the node like this:

    const node = await window.Ipfs.create()
    console.log('starting ipfs', node)
    this.setState({node: node})

so when the component unmounts I closed it like this:

    this.state.node.stop().catch(err => console.error(err))
1 Like