将一个文本文件拆分为多个文本文件nodejs
Split a text file into multiple text files nodejs
我是 NodeJS 的新手。我有一个文本大文件,如下所示,我需要将每个块动态拆分为多个文本文件。我如何使用 Nodejs 实现此目的?
LargeFile.txt
Name: John
Age: 18
Address: Washington
Name: Doe
Age: 23
Name: Randy
Address: Tennessee
预期结果应该是这样
John.txt
Name: John
Age: 18
Address: Washington
Doe.txt
Name: Doe
Age: 23
Randy.txt
Name: Randy
Address: Tennessee
你的问题是用行间距分隔内容吗?如果是这样,您可以使用 split()
方法并将文本拆分为 \n\n
或 \r\n\r\n
(两个换行符)。
// required module
const fs = require('fs');
// read the file content
const str = fs.readFileSync('/path/to/alldata.txt');
// detect newline character
let newline = '\n';
let twonewlines = '\n\n';
if (str.indexOf('\r\n\r\n') > -1) {
newline = '\r\n';
twonewlines = '\r\n\r\n';
}
// split
let arr = str.split(twonewlines);
// save items as new files
arr.forEach((data, idx)=> {
/* format of data will be:
* Name: XX
* Age: YY
* Address: ZZ
*/
// get name
let firstRow = data.slice(0, data.indexOf(newline)); // get "Name: XX"
let name = firstRow.split(': ')[1]; // get "XX"
// write to file
fs.writeFileSync(`/path/to/${name}.txt`, data);
});
您可以使用文件系统 (fs
) 模块的 Promise 或 Callback 版本以获得更好的性能。
我是 NodeJS 的新手。我有一个文本大文件,如下所示,我需要将每个块动态拆分为多个文本文件。我如何使用 Nodejs 实现此目的?
LargeFile.txt
Name: John
Age: 18
Address: Washington
Name: Doe
Age: 23
Name: Randy
Address: Tennessee
预期结果应该是这样
John.txt
Name: John
Age: 18
Address: Washington
Doe.txt
Name: Doe
Age: 23
Randy.txt
Name: Randy
Address: Tennessee
你的问题是用行间距分隔内容吗?如果是这样,您可以使用 split()
方法并将文本拆分为 \n\n
或 \r\n\r\n
(两个换行符)。
// required module
const fs = require('fs');
// read the file content
const str = fs.readFileSync('/path/to/alldata.txt');
// detect newline character
let newline = '\n';
let twonewlines = '\n\n';
if (str.indexOf('\r\n\r\n') > -1) {
newline = '\r\n';
twonewlines = '\r\n\r\n';
}
// split
let arr = str.split(twonewlines);
// save items as new files
arr.forEach((data, idx)=> {
/* format of data will be:
* Name: XX
* Age: YY
* Address: ZZ
*/
// get name
let firstRow = data.slice(0, data.indexOf(newline)); // get "Name: XX"
let name = firstRow.split(': ')[1]; // get "XX"
// write to file
fs.writeFileSync(`/path/to/${name}.txt`, data);
});
您可以使用文件系统 (fs
) 模块的 Promise 或 Callback 版本以获得更好的性能。