UNPKG

scryinfo

Version:

A real data storage library on ethereum

55 lines (47 loc) 1.78 kB
/** en: ScryDBIPFS is a subclass of ScryDBBase, it has achieved 'get' and 'set' functions through IPFS. @author Danny Yan @date 2017-07 */ var util = require('util'); var fs = require("fs"); var Status = require("../scryStatus.js"); var ScryDBBase = require("./scryDBBase.js"); var ipfsAPI = require('ipfs-api'); var concat = require("concat-stream"); function ScryDBIPFS() { } util.inherits(ScryDBIPFS, ScryDBBase); ScryDBIPFS.prototype.connect = function(url, callback) { this.ipfs = ipfsAPI(url); callback(this.ipfs != null); }; ScryDBIPFS.prototype.get = function(key, callback) { this.ipfs.files.get(key.substring(2), function(err, stream) { if (err) { console.log("接收到ipfs数据错误", err); typeof(callback) == "function" && callback(Status.returnError( err.toString(), err)); return; } stream.on('data', (file) => { file.content.pipe(concat((content) => { console.log("接收到ipfs数据成功:", file.path); typeof(callback) == "function" && callback(Status.returnOK( content.toString() )); })); }) }); }; ScryDBIPFS.prototype.set = function(content, callback) { var buffered = Buffer.from(content); // 保存到ipfs this.ipfs.files.add(buffered, function(err, _files) { if (err) { typeof(callback) == "function" && callback(Status.returnError(err)); console.log("ipfs存储失败:", err); return; } console.log("存储到ipfs数据成功:", _files[0].hash); typeof(callback) == "function" && callback(Status.returnOK( "SC"+_files[0].hash )); }); }; module.exports = ScryDBIPFS;