This is a code snippet I from the code I was given by a friend. I'd appreciate if someone could explain as to what is happening in there in detail. Thanks.
module.exports.loadDb = function (dbFile, cb) {
fs.readFile(dbFile, function (err, res) {
if (err) { return cb(err) }
var messages
try {
messages = JSON.parse(res)
} catch (e) {
return cb(err)
}
return cb(null, { file: dbFile, messages: messages })
})
}
This function is being used to get to the inbox stored in a JSON file but what exactly is going on in there??
module.exports.findInbox = function (db, encodedName) {
var messages = db.messages
return {
dir: path.dirname(db.file),
messages: Object.keys(messages).reduce(function (acc, key) {
if (messages[key].to === encodedName) {
return acc.concat({
hash: key,
lastHash: messages[key].last,
from: messages[key].from
})
} else { return acc }
}, [])
}
}
module.exports.findNextMessage = function (inbox, lastHash) {
// find the message which comes after lastHash
var found
for (var i = 0; i < inbox.messages.length; i += 1) {
if (inbox.messages[i].lastHash === lastHash) {
found = i
break
}
}
// read and decode the message
return 'from: ' + decode(inbox.messages[found].from) + '\n---\n' +
decode(fs.readFile(path.join(inbox.dir, inbox.messages[found].hash), 'utf8'))
}
via Farhat Nawaz
No comments:
Post a Comment