Search code examples
javascriptnode.jsencodingbufferspecial-characters

Getting extra characters when slicing buffers with double quotes in nodejs


Im trying to crop a javascript object (stringified) to a determined size (specifically for Apple Push Notification 256 Max), however i just discovered that when my one of the variables have a string that contains double quotes it gets an extra character that mess with the limit, in the following example i replicated it have a 30 size limit

var object = {"hola":"mundo", "data":""}

var objectBuffer = new Buffer(JSON.stringify(object))
    console.log(objectBuffer.length) // this should be 26 OK

var data0 = new Buffer('normal', 'utf-8')
console.log(data0.length) // this should be 6 OK

var data1 = new Buffer('"normal', 'utf-8') // Note extra double quote (it only happends with double quotes weird characters like ó work ok)
console.log(data1.length) // this should be 7 OK

object.data = data0.toString('utf-8', 0, 4)
console.log(object) // {hola:'mundo', data:'norm'} OK

var objectBuffer = new Buffer(JSON.stringify(object))
console.log(objectBuffer.length) // this should be 30 OK

object.data = data1.toString('utf-8', 0, 4)
console.log(object) // {hola:'mundo', data:'"norm'} OK

var objectBuffer = new Buffer(JSON.stringify(object))
console.log(objectBuffer.length) // this should be 30 NOT OK got 31 instead

Solution

  • You can use a custom replacer for the special characters and passing that function in the JSON.stringify method:

    See the following section: "Example of using replacer parameter JSON.stringify(javascriptObject, method);"

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

    
        function replacer(key, value) {
            if (typeof value === "string") {
                return undefined;
            }
            return value;
        }
    
        var foo = {foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7};
        var jsonString = JSON.stringify(foo, replacer);