访问由回调函数之外的node.js中的readline和fs解析的数据

时间:2022-04-17 12:57:27

This question is different from the one linked as already having an answer. It is specifically this piece of code adapted from node.js documentation regarding the use of fs and readfile and looking for an end of file flag, which I've learned is readfile.close method. Thanks for the answer.

这个问题与已经有答案的链接不同。特别是这段代码改编自node.js文档,关于使用fs和readfile以及查找文件结束标志,我学到的是readfile.close方法。感谢你的回答。

I wrote a small utility locally to try to convert a text file of key:value pairs with a blank line separating programs into a JSON file to use in a React project.

我在本地编写了一个小实用程序,试图转换一个key:value对的文本文件,其中一个空白行将程序分隔成一个JSON文件,以便在React项目中使用。

I got the foundation of the readline function directly from node.js documentation. I'm using node 6.9.0 on my mac

我直接从node.js文档中获得了readline函数的基础。我在我的mac上使用节点6.9.0

here is the full script:

这是完整的脚本:

const readline = require('readline');
const fs = require('fs');

const rl = readline.createInterface({
  input: fs.createReadStream('usat-ncaa-programs.txt')
});

var newPairs=["test"];
rl.on('line',
  function (line) {
  if (line===null){
    newPairs.push("}], [ {")
  } else if (line) {
    var keyValue = line.match(/^(.*):(.*)/)
    var newKeyValuePair =  "'" + keyValue[1].trim() + "':  '" + keyValue[2].trim() + "'"
    newPairs.push(newKeyValuePair)
    //console.log (newKeyValuePair)
  }

})

console.log(newPairs)

The input file looks like this (there are about 12 programs), i've only included 2 1/2 so you can see the format:

输入文件看起来像这样(大约有12个程序),我只包括2 1/2,所以你可以看到格式:

University: Arizona State University
Division: I
University Home Page: http://www.asu.edu/
Recruiting Link: https://questionnaire.acsathletics.com/Questionnaire/Questionnaire.aspx?&SPSID=1061112&SPID=177408&DB_LANG=C&DB_OEM_ID=30300&q=2015&s=159130&o=143
Team Homepage: http://www.thesundevils.com/index.aspx?path=triathlon
Head Coach: Cliff English
w: 480.965.0546
e: cliff.endlish@asu.edu
bg-color: #990033
color: #FFB310

University: Belmont Abby College
Division: II
University Home Page: http://belmontabbeycollege.edu/
Recruiting Link: https://coach.scoutforce.com/p/414f3219dd
Team Homepage: http://abbeyathletics.com/sports/wtri/index
Head Coach: Nick Radkewich
w: 704.461.5010
e: NicholasRadewich@bac.edu
Twitter: https://twitter.com/AbbeyTri
bg-color: #FFFDD0
color: #DC143C

University:Black Hills State University 
Division: II
University Home Page: http://www.bhsu.edu/
...

My problem is that while I can read the text file line by line and parse some information that looks like a JSON file, I am unable to access that data outside of the callback function.

我的问题是,虽然我可以逐行读取文本文件并解析一些看起来像JSON文件的信息,但我无法在回调函数之外访问该数据。

I don't know how to save this data into a new file, or even just output the object to my console for a cut & paste and manually edit.

我不知道如何将这些数据保存到新文件中,或者甚至只是将对象输出到我的控制台进行剪切和粘贴并手动编辑。

In teh above script the logged output of the variable newPairs is ["test"] rather than the line by line parsing that I'm trying to acccomplish.

在上面的脚本中,变量newPairs的记录输出是[“test”],而不是我试图完成的逐行解析。

If I place the console.log inside the callback, I get information logged with every iteration of the file read. I only want to work with the data when the file is done.

如果我将console.log放在回调中,我会在读取的每次迭代中记录信息。我只想在文件完成后处理数据。

I did not find an EOF or similar flag in the node documentation for either fs or readline.

我没有在fs或readline的节点文档中找到EOF或类似的标志。

Additionally, if there is an easier way to get the data I am inputting into JSON format, I'd love to hear. Thanks in advance.

此外,如果有一种更简单的方法来获取我输入JSON格式的数据,我很乐意听到。提前致谢。

1 个解决方案

#1


1  

You have to understand that the callback function is executed asynchronously. This means that console.log(newPairs) gets executed before your callback, therefore it only results in "test".

您必须了解回调函数是异步执行的。这意味着console.log(newPairs)在回调之前执行,因此它只会导致“test”。

You should listen to Readline's close event, like so:

您应该听Readline的关闭事件,如下所示:

rl.on('close', function() {
  console.log(newPairs);
});

As the documentation states:

正如文件所述:

The 'close' event is emitted when one of the following occur:

发生以下任一情况时会发出'close'事件:

  • The rl.close() method is called and the readline.Interface instance has relinquished control over the input and output streams;
  • 调用rl.close()方法,readline.Interface实例放弃了对输入和输出流的控制;

  • The input stream receives its 'end' event; The input stream receives -D to signal end-of-transmission (EOT);
  • 输入流接收其“结束”事件;输入流接收-D信号传输结束(EOT);

  • The input stream receives -C to signal SIGINT and there is no SIGINT event listener registered on the readline.Interface instance.
  • 输入流接收-C以发信号SIGINT,并且在readline.Interface实例上没有注册SIGINT事件监听器。

  • The listener function is called without passing any arguments.
  • 在不传递任何参数的情况下调用侦听器函数。

The readline.Interface instance should be considered to be "finished" once the 'close' event is emitted.

一旦发出'close'事件,readline.Interface实例应被视为“已完成”。

So this would be the 'EOF' you're looking for :-)

所以这将是你正在寻找的'EOF':-)

#1


1  

You have to understand that the callback function is executed asynchronously. This means that console.log(newPairs) gets executed before your callback, therefore it only results in "test".

您必须了解回调函数是异步执行的。这意味着console.log(newPairs)在回调之前执行,因此它只会导致“test”。

You should listen to Readline's close event, like so:

您应该听Readline的关闭事件,如下所示:

rl.on('close', function() {
  console.log(newPairs);
});

As the documentation states:

正如文件所述:

The 'close' event is emitted when one of the following occur:

发生以下任一情况时会发出'close'事件:

  • The rl.close() method is called and the readline.Interface instance has relinquished control over the input and output streams;
  • 调用rl.close()方法,readline.Interface实例放弃了对输入和输出流的控制;

  • The input stream receives its 'end' event; The input stream receives -D to signal end-of-transmission (EOT);
  • 输入流接收其“结束”事件;输入流接收-D信号传输结束(EOT);

  • The input stream receives -C to signal SIGINT and there is no SIGINT event listener registered on the readline.Interface instance.
  • 输入流接收-C以发信号SIGINT,并且在readline.Interface实例上没有注册SIGINT事件监听器。

  • The listener function is called without passing any arguments.
  • 在不传递任何参数的情况下调用侦听器函数。

The readline.Interface instance should be considered to be "finished" once the 'close' event is emitted.

一旦发出'close'事件,readline.Interface实例应被视为“已完成”。

So this would be the 'EOF' you're looking for :-)

所以这将是你正在寻找的'EOF':-)