UNPKG

@coboxcoop/space

Version:

a peer-to-peer private and encrypted space

72 lines (58 loc) 1.38 kB
const rimraf = require('rimraf') const debug = require('@coboxcoop/logger')('cleanup') const tmpdir = require('tmp').dirSync const mkdirp = require('mkdirp') function cleanup (dirs, cb) { if (!cb) cb = noop if (!Array.isArray(dirs)) dirs = [dirs] var pending = 1 function next (n) { var dir = dirs[n] if (!dir) return done() ++pending process.nextTick(next, n + 1) rimraf(dir, (err) => { if (err) return done(err) done() }) } function done (err) { if (err) { pending = Infinity return cb(err) } if (!--pending) return cb() } next(0) } function tmp () { var path = '.'+tmpdir().name mkdirp.sync(path) return path } function replicate (a, b, opts, cb) { if (typeof opts === 'function') return replicate(a, b, {}, opts) if (!cb) cb = noop var s = a.replicate(true) var d = b.replicate(false) var pending = 2 s.pipe(d).pipe(s) .on('remote-feeds', done) .on('remote-feeds', done) function done (key, err) { debug('replicate: ', err ? 'FAIL' : 'SUCCESS') if (err) return cb(err) setTimeout(() => { if (!--pending) { s.end() cb() } }, 100) } } function uniq (array) { if (!Array.isArray(array)) array = [array] return Array.from(new Set(array)) } function noop () {} module.exports = { cleanup, tmp, replicate, uniq }