ipfs-file-manager/send.js

47 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() {
2023-06-19 02:22:42 +00:00
this.node = null;
}
async initIPFS() {
this.node = await create();
console.log('IPFS node is ready');
}
async addFileToIPFS(filePath) {
2023-06-19 02:22:42 +00:00
try {
await this.initIPFS();
const fileData = await this.readFile(filePath);
2023-06-19 02:22:42 +00:00
const results = await this.node.add({ content: fileData });
const cid = results.cid.toString();
console.log('File added to IPFS with CID:', cid);
} catch (error) {
console.error('Failed to add the file to IPFS', error);
} finally {
this.closeIPFS();
}
}
async readFile(filePath) {
try {
return await readFile(filePath);
} catch (error) {
throw new Error(`Failed to read the file: ${error}`);
2023-06-19 02:22:42 +00:00
}
}
async closeIPFS() {
if (this.node) {
await this.node.stop();
console.log('IPFS node connection closed');
}
}
}
const filePath = './image.jpg';
const ipfsFileManager = new IPFSFileManager();
ipfsFileManager.addFileToIPFS(filePath);