Refactor IPFSFileManager class in send.js

This commit is contained in:
Luiz F Picolo 2023-06-20 14:14:42 -04:00
parent fc549dd56c
commit 8289c1982b
1 changed files with 16 additions and 17 deletions

33
send.js
View File

@ -2,8 +2,7 @@ import { create } from 'ipfs';
import { readFile } from 'fs/promises'; import { readFile } from 'fs/promises';
class IPFSFileManager { class IPFSFileManager {
constructor(filePath) { constructor() {
this.filePath = filePath;
this.node = null; this.node = null;
} }
@ -12,25 +11,25 @@ class IPFSFileManager {
console.log('IPFS node is ready'); console.log('IPFS node is ready');
} }
async readFile() { async addFileToIPFS(filePath) {
try {
const data = await readFile(this.filePath);
return data;
} catch (error) {
throw new Error(`Failed to read the file: ${error}`);
}
}
async addFileToIPFS() {
try { try {
await this.initIPFS(); await this.initIPFS();
const fileData = await this.readFile(); const fileData = await this.readFile(filePath);
const results = await this.node.add({ content: fileData }); const results = await this.node.add({ content: fileData });
const cid = results.cid.toString(); const cid = results.cid.toString();
this.closeIPFS();
console.log('File added to IPFS with CID:', cid); console.log('File added to IPFS with CID:', cid);
} catch (error) { } catch (error) {
console.error('Failed to add the file to IPFS', error); console.error('Failed to add the file to IPFS', error);
} finally {
this.closeIPFS();
}
}
async readFile(filePath) {
try {
return await readFile(filePath);
} catch (error) {
throw new Error(`Failed to read the file: ${error}`);
} }
} }
@ -42,6 +41,6 @@ class IPFSFileManager {
} }
} }
const filePath = './file.txt'; const filePath = './image.jpg';
const ipfsFileManager = new IPFSFileManager(filePath); const ipfsFileManager = new IPFSFileManager();
ipfsFileManager.addFileToIPFS(); ipfsFileManager.addFileToIPFS(filePath);