Nodejs encoding issue

260 Views Asked by At

I'm trying to get data from a request, but the formatting or encoding isn't what I'm looking for.

I've tried to set the encoding using req.setEncoding('utf8')

The string I should be getting is: import Graphics.Element exposing (..) import Graphics.Collage exposing (..) import Color exposing (..) main : Element main = collage 500 500 [filled orange (circle (1 + 49)]

What I am actually getting is: import+Graphics.Element+exposing+%28..%29%0D%0Aimport+Graphics.Collage+exposing+%28..%29%0D%0Aimport+Color+exposing+%28..%29%0D%0Amain+%3A+Element%0D%0Amain+%3D+collage+500+500+%5Bfilled+orange+%28circle+%281+%2B+49%29%5D

This is where I read the data and set the encoding:

function onPost () {
// When there is a POST request
app.post('/elmsim.html',function (req, res) {
    console.log('POST request received from elmsim')
    req.setEncoding('ascii')
    req.on('data', function (data) {
        // Create new directory
        createDir(data, res)
    })
})

}

Any help would be great! Thanks

2

There are 2 best solutions below

0
On BEST ANSWER

Luca's answer is correct, but decodeURIComponent will not work for strings including a plus sign. You must split the string using '%2B' as a splitter (This represents a plus sign) and apply decodeURIComponent to each individual string. The strings can then be concatenated, and the plus signs can be added back.

This is my solution:

function decodeWithPlus(str) {
    // Create array seperated by +
    var splittedstr = str.split('%2B')

    // Decode each array element and add to output string seperated by '+'
    var outs = ''
    var first = true
    splittedstr.forEach(function (element) {
        if (first) {
            outs += replaceAll('+', ' ', decodeURIComponent(element))
            first = false
        }
        else {
            outs += '+' + replaceAll('+', ' ', decodeURIComponent(element))
        }
    })
    return outs
}

function replaceAll(find, replace, str) {
    var outs = ''
    for (i = 0; i < str.length; i++) {
        if (str[i] === find) {
            outs += replace
        }
        else {
            outs += str[i]
        }
    }
    return outs
}
3
On

The string you are getting is an url encoded string.

Have you try to call decodeUriComponent on the string?

decodeURIComponent( string )