iota-reader
Version:
Command line utility to download mam streams that contain json data to a json file.
82 lines (76 loc) • 2.12 kB
JavaScript
const Mam=require('@iota/mam')
const { asciiToTrytes, trytesToAscii } = require('@iota/converter')
const mode='public'
const provider='https://dyn.tangle-nodes.com'
//const root = 'HNWCIUCQGMMNGORVVVUTL9SSXDELAUASOJIEAWQOUJHLYLDGNWFIPKVERG9RKQDDWHGGPZGSQ9MEZPNIY'
//const root='HI9FKCXRDNFWHCICCFADORCECRXKLQ9CUGYIDGANCKBUXDKSCBFKIAKYOQNWFRQOJDKNPHRHBLJEMYPNC'
const root = 'YBLXOSGIETIJHYEIXREDROOLKZDWIDFIUWVVYUGURWQZOJXK9QZXKXGDUSQFBZP9ADELMHMUPN9ZKEWMI'
let mamState=Mam.init(provider)
const log = data=>console.log(JSON.parse(trytesToAscii(data)),'\n')
var fs = require('fs')
function parseMsg(msg){
try{
return JSON.parse(JSON.parse(trytesToAscii(msg)))
}catch(error){
return undefined
}
}
async function init(thisRoot,write=null,filename=null){
console.log("initialized on",thisRoot)
latestRoot=thisRoot
try{
await Mam.fetch(thisRoot,mode,null,m=>{
if (m != undefined){
try{
msg=parseMsg(m)
if (msg != undefined){
console.log("Recieved message",msg)
if(write!=null){
write(msg,filename)
}
}else{
console.log("Problem with message",msg)
}
}catch(error){
console.log("Failed to parse.")
}
}else{
console.log("Message Undefined")
}
})
.then(response=>{
if (response.messages != undefined && response.messages.length != 0){
latestRoot=response.nextRoot
init(response.nextRoot,write,filename)
}else{
console.log("Failed to retrieve. Retrying...")
init(latestRoot,write,filename)
}
})
.catch(err=>{
console.log("MAM broke, retry.")
init(latestRoot,write,filename)
})
}catch(error){
console.log("Message Broken.")
}
}
function append(data,filename){
if(fs.existsSync(filename)){
fs.readFile(filename,{encoding: 'utf-8'},function(err,d){
if (!err){
myFile=JSON.parse(d)
myFile.push(data)
fs.writeFile(filename,JSON.stringify(myFile),console.log)
}
})
}
else{
fs.writeFile(filename,JSON.stringify([data]),console.log)
}
}
if (process.argv.length >= 3){
init(root,append,process.argv[2])
}else{
init(root)
}