简体   繁体   中英

“read” in Node.js REPL

Is there a function in Node.js that reads characters from a stream until it reads a complete JavaScript expression and returns that expression? The "read" part of the read-eval-print loop?

I want to read JSON objects from a stream and process them as they come in. I don't need the interactive parts of REPL in this use case.

{"r": 0.0,
 "e": -0.2,
 "t": 0.98}
// callback happens here with the content of the object

{"r": 0.2,
 "e": 0.0,
 "t": 1.0}
// callback happens here with the content of the object
// etc

A complete Javascript expression is not necessarily a valid JSON serialization, eg { foo: 'bar' } is a valid JS expression, but invalid JSON (JSON requires double-quoted object keys and string literals). If you know that your JSON objects will always end on a newline boundary, you can accumulate lines in a variable, trying to JSON.parse() it until you succeed (an unsuccessful JSON.parse() would throw a SyntaxError ), but that would not allow you to detect errors in your input (you'll just accumulate lines forever). If you provide more details about what and how exactly you expect to receive, there might be other, more suitable approaches.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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