nodejs:解析json的块

时间:2015-08-31 22:25:57

标签: json node.js

我创建了一个发送字符串化JSON块的测试服务器。当我连接到服务器时,它发送无效的JSON,在我的生活中,我无法弄清楚为什么。输出添加了一个额外的双引号。

服务器代码:

const net = require('net'),
server = net.createServer(function(connection) {
    console.log('subscriber connected.');

    // send first chunk immediately
    connection.write('{"type":"changed","file":"targ"');

    let timer = setTimeout(function() {
        connection.write('et.txt","timestamp":1358175758495}' + '\n');
        connection.end();
    }, 1000);

    connection.on('end', function() {
        clearTimeout(timer);
        console.log('subscriber disconnected');
    });
});

server.listen(5432, function() {
    console.log('test server listening for subs...')
});

ldj.js

'use strict';
const
    events = require('events'),
    util = require('util'),
    // client constructor
    LDJClient = function(stream) {
        events.EventEmitter.call(this);
        let self = this;
        let buffer = '';

        stream.on('data', function(data) {

            buffer += data;
            console.log(buffer)
            let boundary = buffer.indexOf('\n');
            while(boundary !== -1) {
                let input = buffer.substr(0, boundary);
                buffer = buffer.substr(boundary + 1);
                //self.emit('message', JSON.parse(input));
                boundary = buffer.indexOf('\n');
            }
        });
    };

util.inherits(LDJClient, events.EventEmitter);

// expose module methods
exports.LDJClient = LDJClient;
exports.connect = function(stream) {
    return new LDJClient(stream);
};

输出:

{"type":"changed","file":"targ"
{"type":"changed","file":"targ"et.txt","timestamp":1358175758495}

额外的“不应该在”target.txt“值。任何想法?

TIA

1 个答案:

答案 0 :(得分:0)

而不是分裂字符串manualy尝试获取整个字符串并将其拆分为块然后发送它:

var data = '{"type":"changed","file":"target.txt","timestamp":1358175758495}';
var chunks = data.match(/.{1,10}/g); // 10 symbol chunks
for(var i = 0; i < chunks.length; i++) {
  var chunk = chunks[i];
  setTimeout(function() {
    if(connection) {
      connection.write(chunk+'\n');
      if(i + 1 == chunks.length) {
        connection.end();
      } 
    }
  }, i*1000);
}

connection.on('end', function() {
    console.log('subscriber disconnected');
});