ipfs-file-manager/send.js

48 lines
1.1 KiB
JavaScript
Raw Normal View History

2023-06-19 02:22:42 +00:00
import { create } from 'ipfs';
2023-06-20 17:46:59 +00:00
import { readFile } from 'fs/promises';
2023-06-19 02:22:42 +00:00
class IPFSFileManager {
constructor(filePath) {
this.filePath = filePath;
this.node = null;
}
async initIPFS() {
this.node = await create();
console.log('IPFS node is ready');
}
2023-06-20 17:46:59 +00:00
async readFile() {
try {
const data = await readFile(this.filePath);
return data;
} catch (error) {
throw new Error(`Failed to read the file: ${error}`);
}
2023-06-19 02:22:42 +00:00
}
async addFileToIPFS() {
try {
await this.initIPFS();
const fileData = await this.readFile();
const results = await this.node.add({ content: fileData });
const cid = results.cid.toString();
this.closeIPFS();
console.log('File added to IPFS with CID:', cid);
} catch (error) {
console.error('Failed to add the file to IPFS', error);
}
}
async closeIPFS() {
if (this.node) {
await this.node.stop();
console.log('IPFS node connection closed');
}
}
}
const filePath = './file.txt';
const ipfsFileManager = new IPFSFileManager(filePath);
ipfsFileManager.addFileToIPFS();