ipfs-file-manager/retrive.js

55 lines
1.4 KiB
JavaScript
Raw Normal View History

2023-06-19 02:22:42 +00:00
import { create } from 'ipfs';
2023-06-20 17:46:59 +00:00
import { writeFile } from 'fs/promises';
2023-06-19 02:22:42 +00:00
class IPFSFileManager {
2023-06-20 17:46:59 +00:00
constructor() {
2023-06-19 02:22:42 +00:00
this.node = null;
}
async initIPFS() {
this.node = await create();
console.log('IPFS node is ready');
}
2023-06-20 17:46:59 +00:00
async retrieveFileFromIPFS(cid, filepath) {
2023-06-19 02:22:42 +00:00
try {
await this.initIPFS();
2023-06-20 17:46:59 +00:00
2023-06-19 02:22:42 +00:00
const chunks = [];
for await (const chunk of this.node.cat(this.cid)) {
chunks.push(chunk);
}
const fileData = Buffer.concat(chunks);
// Save the file data to a local file
const filePath = `./retrievedFile.pdf`;
2023-06-20 17:46:59 +00:00
await this.saveFileToLocal(filePath, fileData);
this.closeIPFS();
2023-06-19 02:22:42 +00:00
console.log('File retrieved from IPFS and saved as:', filePath);
} catch (error) {
console.error('Failed to retrieve the file from IPFS', error);
}
}
2023-06-20 17:46:59 +00:00
async saveFileToLocal(filePath, fileData) {
try {
await writeFile(filePath, fileData);
} catch (error) {
console.error('Failed to save the file locally', error);
throw error;
}
}
async closeIPFS() {
if (this.node) {
await this.node.stop();
console.log('IPFS node connection closed');
}
}
2023-06-19 02:22:42 +00:00
}
const cid = 'QmQgGxzWnzjCfouxRiozBiEG3wcsuJGWjtHjv3wurVbJ9s'; // Replace with the CID of the file you want to retrieve
2023-06-19 02:22:42 +00:00
const ipfsFileManager = new IPFSFileManager(cid);
ipfsFileManager.retrieveFileFromIPFS();