基於js-ipfs-api實現ipfs的檔案上傳與下載
阿新 • • 發佈:2019-01-25
配置本地的ipfs節點
# 初始化ipfs節點
ipfs init
# 執行ipfs節點
ipfs daemon
使用js-ipfs-api呼叫ipfs服務
連線本地ipfs節點
const ipfsAPI = require('ipfs-api');
const ipfs = ipfsAPI({host: 'localhost', port: '5001', protocol: 'http'});
本地檔案上傳到ipfs,並獲取hash
ipfs.add(fs.readFileSync(path), function (err, files) {
if (err || typeof files == "undefined") {
console.log(err);
} else {
console.log(files);
}
})
通過hash從ipfs獲取資料,並儲存為本地檔案
ipfs.get(hash,function (err,files) {
if (err || typeof files == "undefined") {
console.log(err);
} else {
console.log(files);
}
})
使用promise進行封裝呼叫
ipfsFile.js
const ipfsAPI = require('ipfs-api');
const ipfs = ipfsAPI({host: 'localhost', port: '5001', protocol: 'http'});
exports.add = (buffer) =>{
return new Promise((resolve,reject)=>{
try {
ipfs.add(buffer, function (err, files) {
if (err || typeof files == "undefined") {
reject(err);
} else {
resolve(files[0].hash);
}
})
}catch(ex) {
reject(ex);
}
})
}
exports.get = (hash) =>{
return new Promise((resolve,reject)=>{
try{
ipfs.get(hash,function (err,files) {
if (err || typeof files == "undefined") {
reject(err);
}else{
resolve(files[0].content);
}
})
}catch (ex){
reject(ex);
}
});
}
index.js
const ipfsFile = require('./ipfsFile');
const fs = require('fs');
//操作檔案
let addPath = "./storage/add/onepiece.jpg";
let getPath = "./storage/get/onepiece.jpg";
let buff = fs.readFileSync(addPath);
ipfsFile.add(buff).then((hash)=>{
console.log(hash);
console.log("http://localhost:8080/ipfs/"+hash);
return ipfsFile.get(hash);
}).then((buff)=>{
fs.writeFileSync(getPath,buff);
console.log("file:"+getPath);
}).catch((err)=>{
console.log(err);
})
//操作內容
let User = {
"name":"naruto",
"age":23,
"level":"ss"
};
buff = Buffer.from(JSON.stringify(User));
ipfsFile.add(buff).then((hash)=>{
console.log(hash);
console.log("http://localhost:8080/ipfs/"+hash);
return ipfsFile.get(hash);
}).then((buff)=>{
let obj = JSON.parse(buff.toString('utf-8'));
console.log(obj);
}).catch((err)=>{
console.log(err);
})