swarm-api/bin/swarmapi

69 lines
1.6 KiB
Plaintext
Raw Normal View History

#!/usr/bin/env node
2018-09-11 02:38:47 +00:00
const SwarmAPI = require('../src/index.js');
const swarmhash = require('swarmhash');
const fs = require('fs');
const yargs = require('yargs')
.usage('Usage: $0 [command]')
.command('get <gateway> <hash>', 'Download content', {
gateway: {
alias: 'g',
default: 'http://swarm-gateways.net'
},
hash: {
alias: 'h'
}
})
.command('put <gateway> <filename>', 'Upload file', {
gateway: {
alias: 'g',
default: 'http://swarm-gateways.net'
},
filename: {
alias: 'f'
}
})
.command('calculate <filename>', 'Calculate the hash only without uploading')
.strict()
.version()
.showHelpOnFail(false, 'Specify --help for available options')
.help()
.demand(1, 'Must provide a command');
const argv = yargs.argv;
const gateway = argv.gateway;
const command = argv._[0];
2018-09-11 02:38:47 +00:00
const swarmapi = new SwarmAPI({gateway});
function abort(msg) {
console.log(msg || 'Error occured');
process.exit(1);
}
switch (command) {
case 'get':
2018-09-11 02:38:47 +00:00
swarmapi.downloadRaw(argv.hash, function (err, ret) {
if (err) {
abort('Failed to download: ' + err);
} else {
console.log(ret);
}
});
break;
case 'put':
2018-09-11 02:38:47 +00:00
swarmapi.uploadRaw(fs.readFileSync(argv.filename), function (err, ret) {
if (err) {
console.log('Failed to upload: ' + err);
} else {
console.log('Swarm hash: ' + ret);
}
});
break;
case 'calculate':
console.log('Swarm hash: ' + swarmhash(fs.readFileSync(argv.filename)).toString('hex'));
break;
default:
2018-09-11 02:38:47 +00:00
console.log('Invalid arguments. Type \'swarmapi --help\' for valid options');
}