Streaming / Piping JSON.stringify output in Node.js / Express

后端 未结 2 681
别那么骄傲
别那么骄傲 2020-12-14 21:13

I have a scenario where I need to return a very large object, converted to a JSON string, from my Node.js/Express RESTful API.

res.end(JSON.stringify(obj));
         


        
相关标签:
2条回答
  • 2020-12-14 21:43

    Ideally, you should stream your data as you have it and not buffer everything into one large object. If you cant't change this, then you need to break stringify into smaller units and allow main event loop to process other events using setImmediate. Example code (I'll assume main object has lots of top level properties and use them to split work):

    function sendObject(obj, stream) {
        var keys = Object.keys(obj);
        function sendSubObj() {
           setImmediate(function(){
              var key = keys.shift();
              stream.write('"' + key + '":' + JSON.stringify(obj[key]));
              if (keys.length > 0) {
                stream.write(',');
                sendSubObj();
              } else {
                stream.write('}');
              }
           });
        })
        stream.write('{');
        sendSubObj();
    } 
    
    0 讨论(0)
  • 2020-12-14 21:43

    It sounds like you want Dominic Tarr's JSONStream. Obviously, there is some assembly required to merge this with express.

    However, if you are maxing out the CPU attempting to serialize (Stringify) an object, then splitting that work into chunks may not really solve the problem. Streaming may reduce the memory footprint, but won't reduce the total amount of "work" required.

    0 讨论(0)
提交回复
热议问题