【发布时间】:2017-12-13 18:09:22
【问题描述】:
我已经编写了一个用于自动化某些事情的小型 nodejs 脚本基本上,它所做的只是:
- 从file1读取并创建一个js对象
- 逐行读取file2,根据之前创建的对象查找替换一些字符串。
- 将该行写入新文件。
虽然上述所有方法都有效,但新文件中的格式与原始文件中的格式不同。我的印象是正在读取的文件是 dos 格式,而正在写入的文件是 unix 格式,但我不确定。
我想按原样保留所有转义字符。我应该做些什么额外的事情?
main.js
var fs = require('fs');
var readline = require('readline');
// get the file names from command line
var micrFileMappings = process.argv[2];
var inputFile = process.argv[3];
var micrObject = {};
// read the first file and create the object.
// the first file format is:
// 121212:2323232,
// 345353:2325646,...
var readMicrFile = readline.createInterface({
input: fs.createReadStream(micrFileMappings),
console: false
});
readMicrFile.on('line', function(line) {
var currentLineArray = line.split(":");
var key = currentLineArray[0];
var value = currentLineArray[1];
//populate the object
micrObject[key] = value;
});
// read the file that is to be processed line by line
var rd = readline.createInterface({
input: fs.createReadStream(inputFile),
console: false
});
rd.on('line', function(line) {
var existingID = line.substring(2, 11);
if (micrObject.hasOwnProperty(existingID)) {
line = line.replace(existingID, micrObject[existingID]);
}
// write line by line to the new file
fs.appendFile('processed.txt', line, function(err) {
if (err) {
// append failed
} else {
// done
}
});
});
我的原始文件如下所示:
od -c original.txt
...
...
...
0002720 5 6 0 0 1 5 1 0 0 5 6
5 6 0 0 1 5 1 0 0 5 6
0002740 0 3 2 3 4 B r u h a t B e n g
0 3 2 3 4 B r u h a t B e n g
0002760 a l u r u M a h 0 0 0 0 0 0 0
a l u r u M a h 0 0 0 0 0 0 0
0003000 0 0 0 6 7 3 0 0 0 0 0 0 3 4 4 5
0 0 0 6 7 3 0 0 0 0 0 0 3 4 4 5
0003020 4 0 0
4 0 0
0003040 \r \n
\r \n
0003054
但我的输出文件如下所示:
...
...
...
0001160 2 2 5 6 0 0 0 2 2 9 1 1 0
0001200 0 2 5 1 0 0 1 0 1 1 0 0 6 3 8 K
0001220 u m a r a S w a m y
0001240
0001260 5 6 0 0 1 5 1 0 0
0001300 5 6 0 3 2 3 4 B r u h a t B e
0001320 n g a l u r u M a h 0 0 0 0 0
0001340 0 0 0 0 0 6 7 3 0 0 0 0 0 0 3 4
0001360 4 5 4 0 0
0001400
0001414
如果您注意到,转义字符 \r \n 会丢失。我该如何保存这个?
【问题讨论】:
-
您能否链接到
original.txt或类似的小示例? -
@ExplosionPills - 我不确定我是否可以在线共享文本文件的确切副本,但让我看看我是否可以获得简化的示例。
标签: javascript node.js newline