From 764f09732683dc10c0ea7ed2f2f7ec570d6e2af7 Mon Sep 17 00:00:00 2001 From: "Luiz F. Picolo" Date: Tue, 20 Jun 2023 13:46:59 -0400 Subject: [PATCH] Added better pratices --- retrive.js | 21 +++++++++++++++------ send.js | 20 ++++++++------------ 2 files changed, 23 insertions(+), 18 deletions(-) diff --git a/retrive.js b/retrive.js index ce3d285..1cbf70a 100644 --- a/retrive.js +++ b/retrive.js @@ -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,8 +23,8 @@ 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); } catch (error) { @@ -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(); diff --git a/send.js b/send.js index 0a94795..fa42ced 100644 --- a/send.js +++ b/send.js @@ -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();