简体   繁体   English

如何在node.js中添加换行符?

[英]How to append new line character in node.js?

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. 我是node.js的新手,我正在尝试编写一个接收http请求并通过套接字转发内容的程序。 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 . 到目前为止,它工作正常,除了与内容发送额外的消息: 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. 所以uri.split("=")的输出不能是我所期待的。

I'm sure the new line is there, but you aren't going to see it when you send your Content-Type as text/html . 我确定新行是存在的,但是当你将Content-Type作为text/html发送时,你不会看到它。 In HTML, \\n is just other whitespace, and is treated as such. 在HTML中, \\n只是其他空格,并且被视为这样。 Use text/plain instead. 请改用text/plain

Since content type is 'text/html',we can happily use break statement.Just like this 由于内容类型是'text / html',我们可以愉快地使用break语句。就像这样

res.write('hello'+'<br/>');
 res.write('nice to meet you');

You can try this code in node: 您可以在节点中尝试此代码:

var http = require('http');

http.createServer(function (req, res) {

res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('hello,this is saikiran'+'<br/>');
res.end('nice to meet you');

}).listen(process.env.PORT || 8080);
console.log('server running on port 8080');

根据text / plain的内容类型,您还可以使用\\ r \\ n将返回输入发送到客户端的浏览器

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. 我刚刚过滤了某种格式的请求并修复了它。

考虑使用\\\\n而不是\\n来表示新行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM