Node.js ipfs-api读写文件失败,已用Buffer临时解决求解析
Hey there! Let's break down exactly why you're seeing this behavior with the ipfs-api package:
Core Reason: ipfs-api is an HTTP Client, Not a Local File System Tool
The ipfs-api package acts as a HTTP client that communicates with your local IPFS daemon via its REST API endpoints. It doesn't have direct access to your machine's file system—even though the daemon is running locally, the client and daemon interact over HTTP, which doesn't support reading arbitrary local files directly.
When you pass a raw file path like /tmp/afile.txt to ipfs-api methods (e.g., add), the client can't:
- Access your local file system to read the file's content
- Automatically translate the path into a readable stream or buffer for the IPFS daemon
Instead, it might treat the path as a plain string, or throw an error because it can't resolve the file from its own context.
Why Using Buffers Works
When you manually read the file and convert it to a Buffer first, you're doing two key things:
- Loading the file's content into your application's memory
- Passing that raw content directly to the
ipfs-apiclient
The client can then wrap this Buffer into an HTTP request and send it to the IPFS daemon, which can process the content normally and add it to the IPFS network. This skips the need for the client to access your file system entirely.
Quick Side Note: Using ReadStreams
If you prefer not to load the entire file into memory (great for large files), you can also use Node.js fs.createReadStream() to pass a stream to ipfs-api—this works for the same reason: the stream sends chunks of the file content over HTTP to the daemon, rather than relying on the client to resolve the file path.
内容的提问来源于stack exchange,提问作者Amarsh

