用Node.js编写类似Bash的split命令的处理
首先
在处理Node.js中的大文件时,我希望能像bash的split命令一样,将文件按行分割,所以我创建了这个作为备忘录留下的工具。
它结合了Bash命令和选项,所以可以像在Bash中一样使用它是关键点。
提供以下的中文的同义短语,只需一种选择:
代码
bash的split命令
$ split [OPTION]... [FILE [PREFIX]]
选项(部分)
-
- -l, –lines=NUMBER
分割するファイルの行単位
-d, –numeric-suffixes
指定あり: [PREFIX000, PREFIX001, PREFIX002…]
指定なし: [PREFIXaaa, PREFIXaab, PREFIXaac…]
-a, –suffix-length=N
出力ファイルに付加する文字列の長さ
用Node.js的版本
const fs = require('fs');
const readline = require('readline');
function createAlphabetSuffix(num, length) {
let i = num;
let str = '';
while (i > 0) {
str = String.fromCharCode(97 + (i % 26)) + str;
i = Math.floor(i / 26);
}
return str.padStart(length, 'a');
}
function createNumericSuffix(num, length) {
return String(num).padStart(length, '0');
}
module.exports = function split(file, options = {}) {
return new Promise((resolve) => {
let {
prefix = 'x',
lines = 100,
suffixLength = 3,
numericSuffixes = false
} = options;
const rs = fs.createReadStream(file);
const rl = readline.createInterface(rs);
let index = 0;
let ws;
rl.on('line', (line) => {
let i = index++;
if (i % lines === 0) {
ws && ws.close();
const suffixIndex = Math.floor(i / lines);
const suffix = numericSuffixes
? createNumericSuffix(suffixIndex, suffixLength)
: createAlphabetSuffix(suffixIndex, suffixLength);
ws = fs.createWriteStream(`${prefix}${suffix}`);
}
ws.write(line + '\n');
});
rl.on('close', () => {
ws && ws.close();
resolve();
});
});
};
在中文中进行同义改述时,可以使用以下表达方式:
– 选择
– 选项
– 任选
– 可选项
– 方案
オプション初期値説明prefixx出力するファイルのベース名lines100出力するファイルの行数suffixLength3出力ファイルに付与する文字列の長さnumericSuffixesfalse出力ファイルに付与する文字列を数値にするか
样本
const split = require('./split');
(async () => {
await split('./largeFile.txt', {
prefix: 'smallFile',
lines: 10,
suffixLength: 4,
numericSuffixes: true
});
})();
$ node useSplit.js
$ ls | grep smallFile
# smallFile0000
# smallFile0001
# smallFile0002
# ...
最后
如果尽管意外地找不到,那我就试着自己动手做了。
如果还有其他更好的方法,请指出来。