Get
The Get
command allows you to retrieve the content of objects stored in your DID Space. This is essential for accessing your data, whether it's a file, an image, or any other binary content.
For more information on managing objects, see the Object commands overview. To learn how to upload objects, refer to the Put command.
Get Object Content#
Use the get
method on the object
client to retrieve an object's content. The content is returned as a Node.js Readable
stream, which you can then pipe to a file, process in memory, or stream directly.
Parameters
Name | Type | Description |
---|---|---|
|
| The unique identifier or path of the object to retrieve within your DID Space. |
Returns
Name | Type | Description |
---|---|---|
|
| The HTTP status code of the response (e.g., 200 for success). |
|
| The HTTP status message (e.g., "OK"). |
|
| An object containing the response headers. |
|
| A Node.js |
Example
import { createWriteStream } from 'fs';
import { resolve } from 'path';
import { SpaceClient } from '@did-spaces/client';
import { streamToFile } from '@did-spaces/client/libs/stream'; // Assuming this utility is exported
async function getObjectContent(client, objectKey, outputPath) {
try {
console.log(`Attempting to retrieve object: ${objectKey}`);
const { data: objectStream, statusCode, statusMessage } = await client.object.get({
key: objectKey,
});
if (statusCode === 200) {
console.log(`Successfully retrieved object stream (Status: ${statusCode} ${statusMessage}). Saving to ${outputPath}`);
const writeStream = createWriteStream(outputPath);
objectStream.pipe(writeStream);
await streamToFile(writeStream); // Wait for the stream to finish writing
console.log('Object successfully saved to file.');
} else {
console.error(`Failed to retrieve object. Status: ${statusCode} ${statusMessage}`);
}
} catch (error) {
console.error('Error retrieving object:', error);
}
}
// Example usage:
// Assumes client is already initialized
// const client = new SpaceClient({
// endpoint: 'YOUR_DID_SPACE_ENDPOINT',
// wallet: YOUR_ABT_WALLET_INSTANCE,
// // delegation: YOUR_DELEGATION_OBJECT // Optional
// });
// const myObjectKey = 'path/to/your/file.txt';
// const downloadPath = resolve('./downloaded-file.txt'); // Save to current directory
// getObjectContent(client, myObjectKey, downloadPath);
This example demonstrates how to use the get
command to retrieve an object by its key
. The returned data
is a Readable
stream, which is then piped to a local file using Node.js's createWriteStream
and the streamToFile
utility to ensure the entire content is written before completion.
You have learned how to retrieve objects from your DID Space. Next, you might want to learn how to remove objects using the Delete command or how to list objects within a directory using the List command.