ipfs-file-manager/IPFSFileRetriever.js

68 lines
1.9 KiB
JavaScript
Raw Normal View History

2023-06-20 17:46:59 +00:00
import { writeFile } from 'fs/promises';
import { fileTypeFromBuffer } from 'file-type';
2023-06-20 22:30:55 +00:00
import IPFSManager from './IPFSManager.js';
2023-06-19 02:22:42 +00:00
2023-06-20 22:30:55 +00:00
export default class IPFSFileRetriever extends IPFSManager {
2023-06-20 17:46:59 +00:00
constructor() {
2023-06-20 22:30:55 +00:00
super();
2023-06-19 02:22:42 +00:00
this.node = null;
}
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(cid)) {
2023-06-19 02:22:42 +00:00
chunks.push(chunk);
}
const fileData = Buffer.concat(chunks);
// Determine the file extension based on the MIME type
2023-06-20 22:30:55 +00:00
const mime = await this.getFileTypeFromFile(fileData);
const fileExtension = this.getFileExtension(mime);
// Save the file data to a local file with the appropriate extension
const filePath = `${filepath}.${fileExtension}`;
2023-06-20 17:46:59 +00:00
await this.saveFileToLocal(filePath, fileData);
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);
} finally {
this.closeIPFS();
2023-06-19 02:22:42 +00:00
}
}
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;
}
}
2023-06-20 22:30:55 +00:00
async getFileTypeFromFile(fileData) {
try {
return fileTypeFromBuffer(fileData);
} catch (error) {
console.error('Failed to determine the file type', error);
throw error;
}
}
getFileExtension(mimeType) {
// Map commonly used MIME types to file extensions
const extensionMap = {
'application/pdf': 'pdf',
'image/jpeg': 'jpg',
'image/png': 'png',
'text/plain': 'txt',
// Add more MIME types and extensions as needed
};
// Return the corresponding extension if available, otherwise fallback to 'dat'
return extensionMap[mimeType] || 'dat';
}
2023-06-20 22:30:55 +00:00
}