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 { writeFileSync } from 'fs';
import { writeFile } from 'fs/promises';
class IPFSFileManager {
constructor(cid) {
this.cid = cid;
constructor() {
this.node = null;
}
@ -12,9 +11,10 @@ class IPFSFileManager {
console.log('IPFS node is ready');
}
async retrieveFileFromIPFS() {
async retrieveFileFromIPFS(cid, filepath) {
try {
await this.initIPFS();
const chunks = [];
for await (const chunk of this.node.cat(this.cid)) {
chunks.push(chunk);
@ -23,7 +23,7 @@ class IPFSFileManager {
// Save the file data to a local file
const filePath = `./retrievedFile.pdf`;
writeFileSync(filePath, fileData);
await this.saveFileToLocal(filePath, fileData);
this.closeIPFS();
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() {
if (this.node) {
await this.node.stop();

20
send.js
View File

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