Oh i like that idea. If i did it like you had said then i would maybe pipe to a xml praser or pipe even to a logger.
On Monday, April 30, 2012 6:36:22 PM UTC-4, Marco Rogers wrote: > > There are several potential issues I'm seeing here. But it looks like you > have an incoming stream of json messages that are encrypted and separated > by newlines. You want parse the stream, decrypt each message and then pass > the message to a data handler that expect to each message one by one. Is > that accurate? > > This is a great use case for node streams. Read up on them and create a > stream (or multiple streams) that encapsulates this behavior. You might end > up with a an elegant solution that looks like multiple streams piped > together. > > decryptedStream.on('data', function(data) { > // do something with json object > }); > socket.pipe(messageSplitter).pipe(decrytptedStream) > > Here are some good resources to check out. > > http://nodejs.org/api/stream.html > http://maxogden.com/node-streams > https://github.com/dominictarr/event-stream > > In short, try to separate concerns, splitting the message stream, > decrypting, json parsing, etc. > > :Marco > > > On Monday, April 30, 2012 3:24:37 PM UTC-7, Tim Dickinson wrote: >> >> Oh sorry and you would use it like so >> >> >> socket.on('data', bufferJson(key, function(data) { >> //do something with json object >> })) >> >> On Monday, April 30, 2012 6:23:11 PM UTC-4, Tim Dickinson wrote: >>> >>> Hey all. >>> >>> How can i better write this snippet of code? >>> >>> var bufferJson = function(key, requestEvent) { >>> var buffer = [] >>> var cryptoFn = function(message) { >>> var decipher = crypto.createDecipher('aes-256-cbc', key) >>> return decipher.update(message, 'hex', 'utf8') + >>> decipher['final']('utf8') >>> } >>> function onData(data) { >>> if(data.indexOf('\n') > -1) { >>> >>> var message = buffer.join(''); >>> data = data.split('\n'); >>> message += data.shift(); >>> buffer = []; >>> >>> try { >>> console.log(cryptoFn(message)) >>> var json = JSON.parse(cryptoFn(message)); >>> } catch(e) { >>> return util.error('Could not parse message: ' + e.message); >>> } >>> >>> requestEvent(json) >>> data = data.join('\n'); >>> >>> if(data.length) { >>> onData(data); >>> } >>> >>> } else { >>> buffer.push(data); >>> } >>> } >>> >>> return onData >>> } >>> >> -- Job Board: http://jobs.nodejs.org/ Posting guidelines: https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines You received this message because you are subscribed to the Google Groups "nodejs" group. To post to this group, send email to nodejs@googlegroups.com To unsubscribe from this group, send email to nodejs+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/nodejs?hl=en?hl=en