file-force
94 строки · 2.5 Кб
1/*
2* Copyright (C) 2017 Igor Konovalov
3*
4* Licensed under the Apache License, Version 2.0 (the "License");
5* you may not use this file except in compliance with the License.
6* You may obtain a copy of the License at
7*
8* http://www.apache.org/licenses/LICENSE-2.0
9*
10* Unless required by applicable law or agreed to in writing, software
11* distributed under the License is distributed on an "AS IS" BASIS,
12* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13* See the License for the specific language governing permissions and
14* limitations under the License.
15*/
16
17'use strict';18const fs = require('fs');19const path = require('path');20const getFileName = path.basename;21const ipfs = require('ipfs-api');22const stream = require('stream');23
24function isStream (stream) {25return typeof stream === 'object' && typeof stream.pipe === 'function';26};27
28module.exports = function IPFS(config) {29
30this.instance = ipfs(config.ipfs.api);31
32this.files = this.instance.files;33
34this.addBuffer = (bufferData) => {35const bufferStream = new stream.PassThrough();36bufferStream.end(bufferData);37return this.add(bufferStream);38};39
40this.add = (file) => {41let files;42if (isStream(file)) { // file is stream already43files = [44{45path: file.constructor.name,46content: file47}48];49} else { // prepare stream from file path50const fileStream = fs.createReadStream(file);51const fileName = getFileName(file);52files = [53{54path: fileName,55content: fileStream56}57];58}59return this.instance.add(files);60};61
62/**63* Expose ipfs.get
64* @param hash
65* @param callback
66*/
67this.get = (hash, callback) => {68this.files.get(hash, callback)69};70
71this.cat = (hash, callback) => {72this.files.cat(hash, callback)73};74
75/**76* Store requested hash to file path.
77* @param hash
78* @param localPath
79* @param cb
80*/
81this.getAndStore = (hash, localPath, cb) => {82this.get(hash, (error, stream) => {83let destination = fs.createWriteStream(localPath);84stream.on('data', data => {85data.content.pipe(destination);86});87stream.on('end', () => {88if (cb) {89cb(destination);90}91});92});93}94};