This repository was archived by the owner on Feb 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathutils.js
102 lines (87 loc) · 2.12 KB
/
utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
'use strict'
const fs = require('fs')
const os = require('os')
const APIctl = require('ipfs-api')
const multiaddr = require('multiaddr')
const IPFS = require('../core')
const path = require('path')
const debug = require('debug')
const log = debug('cli')
log.error = debug('cli:error')
const Progress = require('progress')
const byteman = require('byteman')
exports = module.exports
exports.isDaemonOn = isDaemonOn
function isDaemonOn () {
try {
fs.readFileSync(path.join(exports.getRepoPath(), 'api'))
log('daemon is on')
return true
} catch (err) {
log('daemon is off')
return false
}
}
exports.getAPICtl = getAPICtl
function getAPICtl () {
if (!isDaemonOn()) {
throw new Error('daemon is not on')
}
const apiPath = path.join(exports.getRepoPath(), 'api')
const apiAddr = multiaddr(fs.readFileSync(apiPath).toString())
return APIctl(apiAddr.toString())
}
exports.getIPFS = (callback) => {
if (isDaemonOn()) {
return callback(null, getAPICtl(), (cb) => cb())
}
const node = new IPFS({
repo: exports.getRepoPath(),
init: false,
start: false,
EXPERIMENTAL: {
pubsub: true
}
})
const cleanup = (cb) => {
if (node && node._repo && !node._repo.closed) {
node._repo.close(() => cb())
} else {
cb()
}
}
node.on('error', (err) => {
throw err
})
node.once('ready', () => {
callback(null, node, cleanup)
})
}
exports.getRepoPath = () => {
return process.env.IPFS_PATH || os.homedir() + '/.jsipfs'
}
let visible = true
exports.disablePrinting = () => { visible = false }
exports.print = (msg, newline) => {
if (newline === undefined) {
newline = true
}
if (visible) {
if (msg === undefined) {
msg = ''
}
msg = newline ? msg + '\n' : msg
process.stdout.write(msg)
}
}
exports.createProgressBar = (totalBytes) => {
const total = byteman(totalBytes, 2, 'MB')
const barFormat = `:progress / ${total} [:bar] :percent :etas`
// 16 MB / 34 MB [=========== ] 48% 5.8s //
return new Progress(barFormat, {
incomplete: ' ',
clear: true,
stream: process.stdout,
total: totalBytes
})
}