\n 与 \r 的区别
近期的需求用到命令行输出的解析,在解析类似进度条的内容时,遇到一些问题。经过反复的搜索询问,大概得到答案:主要在于 \r 和 \n 的区别。StackOverflow 的一个答案是这么解释的:
As indicated by Peter, CR = Carriage Return and LF = Line Feed, two expressions have their roots in the old typewriters / TTY. LF moved the paper up (but kept the horizontal position identical) and CR brought back the “carriage” so that the next character typed would be at the leftmost position on the paper (but on the same line). CR+LF was doing both, i.e. preparing to type a new line. As time went by the physical semantics of the codes were not applicable, and as memory and floppy disk space were at a premium, some OS designers decided to only use one of the characters, they just didn’t communicate very well with one another ;-)
所以 \r 换行之后,光标移到此行的 0 位,继续输出,于是新的一行会替代旧的一行,形成的效果就是进度条在更新;而 \n 则会另起一行,形成多行输出的效果。
所以类似我这个需求,直接 line.split('\r').pop() 即可。
另外,new TextDecoder('utf-8').decode(binaryData) 返回的文本都是用 \r\n 做换行的。
相关文章
在 WebSocket 中处理二进制文本
我厂产品中有个需求,要用 WebSocket 接收很长的一段文本。生产环境中发现,有些内容发送时会失败,经查,是服务器端进行文本转换时,特殊字符处理存在一些问题。于是决定改为直接发送二进制流,我这边也
聊聊错误/异常处理
又是繁忙的一周。突然发现以前没聊过错误/异常处理,准备分享一下。 这里我就不细究错误(Error)/异常(Ex […]
记一次不成功的数据库搬家
我这个博客始建于 2011 年,当时我从 ZOL 离职,表达欲旺盛的我,希望找个地方继续写博客,于是就买了台集 […]


