UNPKG

nsolid-manager

Version:

A manager that sets up and runs N|Solid for you

99 lines (77 loc) 2.07 kB
import fs from 'fs' import rimraf from 'rimraf' import collect from '../src/collect' import config from '../src/collect/config' import Cache from '../src/collect/cache' // Get config from process.argv const conf = config(process.argv) /** * Configure Storage */ // IIFE required so we can use return to short-circuit ;(function start () { if (!conf.storage) { return onError(new Error('--storage is required')) } if (conf.flush) { // flush persistence dirs if passed --flush flushDir(conf.storage) flushDir(conf.record) } // current state cache const cache = new Cache(conf.storage) cache.restore(e => { if (e && !conf.flush) console.warn('could not load existing cache, starting over') /** * Start polling */ const pollingEmitter = collect.poll(conf, cache) /** * Record hub results on disk */ if (conf.record) { pollingEmitter.on('output', obj => { fs.appendFile(conf.record, JSON.stringify(obj) + '\n', err => { if (err) onError(err) }) }) } /** * Boot server */ collect.createServer(conf, pollingEmitter, cache, onError) .on('listening', function (err) { if (err) return onError(err) const listening = this.address() console.info('Server running on http://%s:%s', listening.address, listening.port) }) }) })() /** * Wipe a directory. * Does nothing if dir is not a string or accessible. */ function flushDir (dir) { if (!dir || typeof dir !== 'string') return try { fs.accessSync(dir) } catch (err) { // ignore err, just return if can't access return } console.info('flushing', dir) rimraf.sync(dir) } /** * Generic CLI Errback handler */ function onError (err) { if (!err) return console.error(err.stack || err) // add helpful suggestions here if (err.code === 'EACCES') { console.error('\nHave you configured a writable --storage directory?') } console.error('\nRun `nsolid-console --help` for command-line help.') process.exit(1) }