Javascript 这种简单的连接有什么问题
我只是尝试使用Node.js在文本文件中连接几行文本。 结果和预期结果如下所示,并不相同。我不知道为什么我会得到我得到的结果,它看起来像是覆盖了前一行 目标:在同一行上连接行和以下子项 app.jsJavascript 这种简单的连接有什么问题,javascript,node.js,Javascript,Node.js,我只是尝试使用Node.js在文本文件中连接几行文本。 结果和预期结果如下所示,并不相同。我不知道为什么我会得到我得到的结果,它看起来像是覆盖了前一行 目标:在同一行上连接行和以下子项 app.js 'use strict' const fs = require('fs') let targetRegex = /Line.*/; let concatStatement = ''; fs.readFileSync('input.txt').toString
'use strict'
const fs = require('fs')
let targetRegex = /Line.*/;
let concatStatement = '';
fs.readFileSync('input.txt').toString().split('\n')
.forEach(function (line) {
if (targetRegex.test(line)) {
concatStatement = line;
}
else {
concatStatement += line
console.log(concatStatement);
}
});
SubA11
SubB22
input.txt
Line11
SubA
Line22
SubB
结果
'use strict'
const fs = require('fs')
let targetRegex = /Line.*/;
let concatStatement = '';
fs.readFileSync('input.txt').toString().split('\n')
.forEach(function (line) {
if (targetRegex.test(line)) {
concatStatement = line;
}
else {
concatStatement += line
console.log(concatStatement);
}
});
SubA11
SubB22
预期的
Line11SubA
Line22Subb
我在ubuntu上试用了这个程序,它产生了您期望的输出 您可能会遇到这样的问题:forEach每次迭代中返回的行变量在开始时有回车符,因为它覆盖了字符 我通过故意在行变量的开头添加回车来验证这一点,它开始生成您得到的输出
'use strict'
const fs = require('fs')
let targetRegex = /Line*/;
let concatStatement = '';
fs.readFileSync('input.txt').toString().split('\n')
.forEach(function (line) {
line = '\r' + line
if (targetRegex.test(line)) {
concatStatement = line;
}
else {
concatStatement += line
console.log(concatStatement);
}
});
这就产生了
SubA11SubB22 如果我评论这句话
line = '\r' + line
然后它(在我的平台上)生成您期望的输出
解决方案
要解决此问题,可以检查input.txt文件的行分隔符,并使用正确的分隔符作为文本拆分