Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to append new line character in node.js?

How to append new line character in node.js?

Problem

I'm new to node.js and I'm trying to write a program that receives http requests and forwards the contents through a socket. At the other end of the socket is a paging system that needs messages terminated with a new line character. So far, it works fine, except there is an extra message sent with the contents: undefined.

When I print the contents of the pager message to the client's browser, there does not appear to be a new line. Am I doing this right?

sys = require("sys"),
http = require("http"),
url = require("url"),
path = require("path"),
net = require("net");

socket = new net.Socket();
socket.connect(4000, '192.168.0.105');

var httpServer = http.createServer(function(request, response) {
    var uri = String(url.parse(request.url).query);
    var message = uri.split("=");
    var page = 'FPG,101,0,3!A' + message[0] + '\n';
    response.writeHead(200, {"Content-Type":"text/html"});
    response.write('sending message: ' + page + " to pager");
    response.end();
    socket.write(page);
}).listen(8080);

sys.puts("Server running at http://localhost:8080/");

EDIT: I narrowed it down further. It turns out that if I do:

var page = 'FPG,101,0,3!A' + 'hello' + '\n';

It works okay. So the output of uri.split("=") must not be what I am expecting.

Problem courtesy of: David

Solution

I figured out what the problem was. For some reason the browser was sending an additional request to the page right after my request. I just filtered for requests with a certain format and that fixed it.

Solution courtesy of: David

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

How to append new line character in node.js?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×