http resonse.write replaces \n with newline

Posted on
  • Hi

    I have a little web server, trying to send \n, \r, \t, \0 .
    But it's being replaced newline, removed, space, nothing.

    While this is the expected behavior for console.log() or print() when sending this data to a client it should arrive at the client (as it does in nodejs), not being replace by something else.

  • (Thanks for sticking the post in here!)

    Please can you post up some minimal example code that does this? Espruino will happily serve up pictures/etc that contain basically random characters, so I'd imagine it is something in the code.

  • I've stripped down my code, same error:

    const WIFI = require("Wifi");
    
    onPageRequest = function(req, res) {
      data = 'foo\nbar\\nfoo';
      res.writeHead(200, {"Content-Type": "text/text", "Content-Length": data.length});
      res.write(data);
      res.end();
    };
    
    startWifi = function() {
      WIFI.connect(ssid, {password: password}, function(err) {
        require("http").createServer(onPageReque­st).listen(80);
        console.log(WIFI.getIP());
      });
    };
    
    ssid = "myssid";
    password = "mypassword";
    startWifi();
    
    /*
    What I get:
    foo
    bar\nbar
    
    What I expected:
    foo\nbar\\nfoo
    */
    
  • Wed 2019.08.07

    Isn't an escaped backslash, the backslash character, so the output is as it should be? (so we see a backslash followed by the letter n - L24)

    https://en.cppreference.com/w/cpp/langua­ge/escape

  • Yepp, that's working as it should work. You would get the same result in every other environment with the same escaping rules. Just try it in a browser console :)
    \n is just a way to write newline character.
    To get foo\nbar\\nfoo you should write foo\\nbar\\\\nfoo.

  • I see where my error is. In nodejs I can load files directly from disc. In Espruino I load my files from the flash using the storage module. And this is read back as string, according to the docs. So my example was actually too short, but the hint regarding strings handling helped. Thanks.

    My fix will be to pre-process the files before storing them to flash, escaping \n etc.

  • Glad it's sorted!

    There's actually a tool online at http://espruino.com/File+Converter that might help you - just upload a file and it'll convert it to a form that is pre-escaped and ready for use.

    There was a plan to add a filesystem organiser to the Web IDE which might help with this sort of thing in future.

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

http resonse.write replaces \n with newline

Posted by Avatar for maze1980 @maze1980

Actions