Added better pratices
This commit is contained in:
parent
aa6c8124fa
commit
764f097326
21
retrive.js
21
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();
|
||||
|
20
send.js
20
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();
|
||||
|
Loading…
Reference in New Issue
Block a user