mik*_*ike 10 javascript node.js
我不知道如何做到这一点.我应该从哪里开始?我用谷歌搜索了这个,并没有提出如何从文本文件中提取随机行的结果.
我发现的唯一的东西是https://github.com/chrisinajar/node-rand-line,但它不起作用.如何从文本文件中读取随机行?
kie*_*ran 11
您可能希望查看node.js标准库函数来读取文件fs.readFile,最后得到以下内容:
//note this will be async
function getRandomLine(filename){
fs.readFile(filename, function(err, data){
if(err) throw err;
var lines = data.split('\n');
/*do something with */ lines[Math.floor(Math.random()*lines.length)];
})
}
Run Code Online (Sandbox Code Playgroud)
如果阅读整个事情并且拆分不是一个选项,那么可能看看这个堆栈溢出的想法.
我也有同样的需求,从超过 100 Mo 的文件中随机挑选一行。
所以我想避免将所有文件内容存储在内存中。
我最终对所有行进行了两次迭代:首先获取行数,然后获取目标行内容。
代码如下:
const readline = require('readline');
const fs = require('fs');
const FILE_PATH = 'data.ndjson';
module.exports = async () =>
{
const linesCount = await getLinesCount();
const randomLineIndex = Math.floor(Math.random() * linesCount);
const content = await getLineContent(randomLineIndex);
return content;
};
//
// HELPERS
//
function getLineReader()
{
return readline.createInterface({
input: fs.createReadStream(FILE_PATH)
});
}
async function getLinesCount()
{
return new Promise(resolve =>
{
let counter = 0;
getLineReader()
.on('line', function (line)
{
counter++;
})
.on('close', () =>
{
resolve(counter);
});
});
}
async function getLineContent(index)
{
return new Promise(resolve =>
{
let counter = 0;
getLineReader().on('line', function (line)
{
if (counter === index)
{
resolve(line);
}
counter++;
});
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7337 次 |
| 最近记录: |