Retrieve File
This script retrieves the contents of a file stored on the Hedera network using a file ID, saves it locally, and logs the size of the retrieved data to the console. It demonstrates how to use the FileContentsQuery to fetch file contents and perform file operations with Hedera.
Step 1: Imports
The script imports necessary modules from the Hedera JavaScript SDK (
@hashgraph/sdk):FileContentsQuery,LocalProvider, andWallet.It also imports the
fsmodule from Node.js for file system operations, and theexitmethod from theprocessmodule.
const {
FileContentsQuery,
LocalProvider,
Wallet
} = require("@hashgraph/sdk");
const fs = require('fs');
const { exit } = require("process");Step 2: Environment Variables Retrieval and Validation
The script loads environment variables from a
.envfile located in theFile_Servicedirectory usingdotenv.It checks whether the required environment variables (
MY_ACCOUNT_IDandMY_PRIVATE_KEY) are present. If not, it throws an error.It retrieves the file ID (
FILE_ID) from the environment variables.
require('dotenv').config({ path: 'File_Service/.env' });
if (process.env.MY_ACCOUNT_ID == null || process.env.MY_PRIVATE_KEY == null) {
throw new Error(
"Environment variables OPERATOR_ID, and OPERATOR_KEY are required."
);
}
const fileId = process.env.FILE_ID;Step 3: Wallet Initialization
It creates a new
Walletinstance using the account ID and private key retrieved from the environment variables.The wallet is initialized with a
LocalProvider, indicating that it will be used for local signing of transactions.
const wallet = new Wallet(
process.env.MY_ACCOUNT_ID,
process.env.MY_PRIVATE_KEY,
new LocalProvider()
);Step 4 : Main Function
It creates a new
FileContentsQueryobject to retrieve the contents of the file specified by the file ID.The file ID is set using the value retrieved from the environment variables.
The query is executed with the signer (wallet) to retrieve the contents of the file.
The size of the retrieved data is logged to the console.
The retrieved contents are then written to a local file named
hedera-retrieved.pdfin theFile_Servicedirectory usingfs.writeFileSync().Finally, the script exits the process.
async function main() {
const query = new FileContentsQuery()
.setFileId(fileId); // Set the file ID to retrieve its contents
const contents = await query.executeWithSigner(wallet); // Execute the query with signer
console.log(`The size of the data is ${contents.length}`);
fs.writeFileSync('File_Service/hedera-retrieved.pdf', contents); // Write the retrieved contents to a local file
process.exit(); // Exit the process
}
Step 5: Execution
This line calls the main() function to start the execution of the script.
main();Last updated
Was this helpful?