简体   繁体   English

Javascript-如何读取文件

[英]Javascript - How to read a file

I am using readline rd.on('line', function(line) {..... to read in a file line by line. I want to then just consume the file one line at a time starting from the first line and proceeding to the end of the file. 我正在使用readline rd.on('line',function(line){.....)逐行读取文件。然后我想从第一行开始一次只消耗一行文件,进行到文件末尾。

It seems "unshift" on an Array (in order to create a Queue to retain the order) can only take a literal and not a variable. 数组上的“ unshift”(为了创建队列以保留顺序)似乎只能采用文字而不是变量。

The main and apparently simplest solution I see for this is to read the file and process int into a string and split(\\n) into an array. 我看到的最简单的主要解决方案是读取文件并将int处理为字符串并将split(\\ n)拆分为数组。

Is there a "better" way? 有没有更好的办法? This seems to consume a huge amount of memory and has limits as a result. 这似乎消耗了大量的内存,因此受到限制。

There is no reason to push your lines after reading them into an array only to read them again. 将它们读入数组后,没有理由只将它们读入数组。 When handling the line event emitted from the readline module simply process the line then. 处理从readline模块发出的line事件时,只需处理该行即可。

Here is the excerpt from the Readline module docs on how to read a file line-by-line: 这是Readline模块文档的摘录,内容涉及如何逐行读取文件:

A common case for readline's input option is to pass a filesystem readable stream to it. readline输入选项的常见情况是将文件系统可读流传递给它。 This is how one could craft line-by-line parsing of a file: 这就是如何逐行分析文件的方式:

 const readline = require('readline'); const fs = require('fs'); const rl = readline.createInterface({ input: fs.createReadStream('sample.txt') }); rl.on('line', (line) => { console.log('Line from file:', line); }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM