Added better pratices

This commit is contained in:
Luiz F Picolo 2023-06-20 13:46:59 -04:00
parent aa6c8124fa
commit 764f097326
2 changed files with 23 additions and 18 deletions

View File

@ -1,9 +1,8 @@
import { create } from 'ipfs'; import { create } from 'ipfs';
import { writeFileSync } from 'fs'; import { writeFile } from 'fs/promises';
class IPFSFileManager { class IPFSFileManager {
constructor(cid) { constructor() {
this.cid = cid;
this.node = null; this.node = null;
} }
@ -12,9 +11,10 @@ class IPFSFileManager {
console.log('IPFS node is ready'); console.log('IPFS node is ready');
} }
async retrieveFileFromIPFS() { async retrieveFileFromIPFS(cid, filepath) {
try { try {
await this.initIPFS(); await this.initIPFS();
const chunks = []; const chunks = [];
for await (const chunk of this.node.cat(this.cid)) { for await (const chunk of this.node.cat(this.cid)) {
chunks.push(chunk); chunks.push(chunk);
@ -23,7 +23,7 @@ class IPFSFileManager {
// Save the file data to a local file // Save the file data to a local file
const filePath = `./retrievedFile.pdf`; const filePath = `./retrievedFile.pdf`;
writeFileSync(filePath, fileData); await this.saveFileToLocal(filePath, fileData);
this.closeIPFS(); this.closeIPFS();
console.log('File retrieved from IPFS and saved as:', filePath); console.log('File retrieved from IPFS and saved as:', filePath);
@ -32,6 +32,15 @@ class IPFSFileManager {
} }
} }
async saveFileToLocal(filePath, fileData) {
try {
await writeFile(filePath, fileData);
} catch (error) {
console.error('Failed to save the file locally', error);
throw error;
}
}
async closeIPFS() { async closeIPFS() {
if (this.node) { if (this.node) {
await this.node.stop(); await this.node.stop();

20
send.js
View File

@ -1,5 +1,5 @@
import { create } from 'ipfs'; import { create } from 'ipfs';
import { readFile as _readFile } from 'fs'; import { readFile } from 'fs/promises';
class IPFSFileManager { class IPFSFileManager {
constructor(filePath) { constructor(filePath) {
@ -12,16 +12,13 @@ class IPFSFileManager {
console.log('IPFS node is ready'); console.log('IPFS node is ready');
} }
readFile() { async readFile() {
return new Promise((resolve, reject) => { try {
_readFile(this.filePath, (error, data) => { const data = await readFile(this.filePath);
if (error) { return data;
reject(error); } catch (error) {
} else { throw new Error(`Failed to read the file: ${error}`);
resolve(data); }
}
});
});
} }
async addFileToIPFS() { async addFileToIPFS() {
@ -48,4 +45,3 @@ class IPFSFileManager {
const filePath = './file.txt'; const filePath = './file.txt';
const ipfsFileManager = new IPFSFileManager(filePath); const ipfsFileManager = new IPFSFileManager(filePath);
ipfsFileManager.addFileToIPFS(); ipfsFileManager.addFileToIPFS();
//ipfsFileManager.closeIPFS();