如何用Node.js将文本文件存入CouchDB及实现后续读取
Fixing Your CouchDB Attachment Upload & Reading Workflow
Let's break down what's going wrong with your attachment upload code, fix it, and then cover how to retrieve the file later.
Why Your insertAttachment Code Isn't Working
First off, the core issues are likely:
- Parameter order mismatch: Most CouchDB Node.js libraries (like the popular
nanopackage) expect a specific order forinsertAttachmentarguments, and yours is out of line. - Incorrect attachment content: You're probably passing the wrong thing as the "attachment body"—it needs to be the actual file content (a Buffer or string), not just a filename.
- Missing document prerequisites: You can't attach a file to a document that doesn't exist. If your target document ID doesn't already exist in CouchDB, you need to create it first to get a valid
_revvalue.
Corrected Upload Code
First, make sure you've installed the nano library (the standard CouchDB client for Node.js):
npm install nano
Here's a complete, working example that writes your file, then uploads it as a CouchDB attachment using async/await for cleaner code:
const fs = require('fs').promises; const nano = require('nano')('http://localhost:5984'); // Replace with your CouchDB URL async function uploadFileToCouchDB() { // Step 1: Write your text file (wait for it to finish writing first) const fileContent = "Your actual file content here"; // Replace with your content await fs.writeFile('file.txt', fileContent); // Step 2: Read the file content as a Buffer (required for attachments) const attachmentBuffer = await fs.readFile('file.txt'); const mimeType = 'text/plain'; // MIME type for text files // Step 3: Connect to your target database const db = nano.db.use('databaseName'); const targetDocId = "document id"; // Your chosen document ID let docRevision; try { // Check if the document already exists to get its revision const existingDoc = await db.get(targetDocId); docRevision = existingDoc._rev; } catch (err) { // If the document doesn't exist, create an empty one to get a valid _rev if (err.statusCode === 404) { const newDoc = await db.insert({}, targetDocId); docRevision = newDoc.rev; } else { throw err; // Re-throw other errors (like connection issues) } } // Step 4: Upload the attachment to CouchDB try { const uploadResponse = await db.attachment.insert( targetDocId, "attachment name", // Name for your attachment (e.g., "my-text-file.txt") attachmentBuffer, mimeType, { rev: docRevision } // Pass the document's revision to avoid conflicts ); console.log("Attachment uploaded successfully:", uploadResponse); } catch (err) { console.error("Failed to upload attachment:", err); } } // Run the upload function uploadFileToCouchDB();
Reading the Attachment from CouchDB
To retrieve your file later, use the attachment.get method to fetch the binary content, then save it back to a local file or process it directly:
async function downloadAttachmentFromCouchDB() { const db = nano.db.use('databaseName'); const targetDocId = "document id"; const attachmentName = "attachment name"; // Match the name you used when uploading try { // Fetch the attachment content as a Buffer const attachmentData = await db.attachment.get(targetDocId, attachmentName); // Save it to a local file await fs.writeFile('downloaded-file.txt', attachmentData); console.log("Attachment downloaded and saved successfully!"); } catch (err) { console.error("Failed to download attachment:", err); } } // Run the download function downloadAttachmentFromCouchDB();
Key Takeaways
- Always pass the actual file content (Buffer/string) as the attachment body, not a filename.
- Double-check parameter order for
insertAttachment:docId → attachmentName → content → mimeType → options (including rev) - Ensure the target document exists before attaching a file—either create an empty document first, or use an existing one's revision.
- Use async/await (or promises) to handle asynchronous file operations and CouchDB requests cleanly.
内容的提问来源于stack exchange,提问作者julia




