How to add a file to existing directory?

Hi IPFS community!

I am quite new, so go easy on me. I am working on an app where I’m using IPFS(js api) and React/Redux.
So my question is: when I’m using the endpoint ipfs.files.add how do I make it possible that the file will be saved to already created directory? I do have my logic wrapped around with wrapWithDirectory (boolean) where i specify my directory in the path but every time I add a new file, there is a new directory hash…

Perhaps my way of doing things is not correct, if so, I would like to hear your opinions/ideas!

Thanks in advance

All nodes have a unique hash. Folders are themselves a node, so when you try to add a file to an IPFS folder, you basically create a new node, with a new hash.

So, lets say you have already created a folder, with the maybe a single file called /foo.txt. Now you want to add another file to this folder called bar.txt. To do this, you’ll need the hash for the file you want to become bar.txt, and to make a DAGLink for usage with object.patch.addLink.

The example over on the API Spec is:

ipfs.object.patch.addLink(node, {
  name: 'some-link'
  size: 10
  multihash: 'QmPTkMuuL6PD8L2SwTwbcs1NPg14U8mRzerB1ZrrBrkSDD'
}, (err, newNode) => {
  if (err) {
    throw err
  }
  // newNode is node with the added link
})

Thank you so much for you answer, I really appreciate it!

I have a follow up question if you don’t mind, regarding the folders: Is creating the ‘‘folder’’ just creating the directory via ipfs.files.mkdir? Or do I actually have to use ipfs.files.add or another API call to create a folder? Because I would like to be able to create an empty folder without any files in it prior to adding a new file to it for example.