【问题标题】:Custom Node JS REPL input/output stream自定义 Node JS REPL 输入/输出流
【发布时间】:2021-08-03 16:15:20
【问题描述】:

我需要自定义 REPL 输入/输出流。例如,当某些事件发生时,我需要将一段脚本传递给 REPL,并获取它的输出并对其进行处理。


为了让您更清楚地描述它,我正在开发一个提供 REPL 的vscode plugin (github: source code)。在我的例子中,我有一个vscode WebView,从那里我得到用户输入,然后我想将该输入传递给节点 REPL 并得到它的输出并将其显示给用户。

那么,我该如何实现呢? 如果您需要更多信息,请告诉我。提前致谢。

编辑 1:

const replServer = repl.start({
    input: /* what should be here? */,
    output: /* what should be here? */
});

编辑 2: 谁能解释一下上面例子中input/output参数的用法?

【问题讨论】:

  • 你是怎么解决这个问题的?
  • @KelvinOmereshone 这个问题没有像我预期的那样解决;相反,我创建了一个自定义 VM。请参阅:stackoverflow.com/questions/67173347/…stackoverflow.com/questions/67322922/context-preserving-eval
  • 有趣的是,我能够自己提供自定义流并且它可以工作,但是出现了范围问题,好像我在第一次运行时声明了一个变量,即使在退出和重启 REPL
  • @KelvinOmereshone 那么您能否与我们分享您的方法来回答这个问题?它会很有价值。

标签: node.js visual-studio-code node-modules read-eval-print-loop node-repl


【解决方案1】:

这是一个对我有用的解决方案。

const {
    PassThrough
} = require('stream')
const repl = require('repl')


const input = new PassThrough()
const output = new PassThrough()

output.setEncoding('utf-8')



const _repl = repl.start({
    prompt: 'awesomeRepl> ',
    input,
    output
})

_repl.on('exit', function() {
    // Do something when REPL exit
    console.log('Exited REPL...')
})


function evaluate(code) {
    let evaluatedCode = ''
    output.on('data', (chunk) => {
        evaluatedCode += chunk.toString()
        console.log(evaluatedCode)

    })

    input.write(`${code}\n`)
    return result

}

evaluate('2 + 2') // should return 4

注意在 evaluate 函数之外创建了 REPL 实例,因此我们不会为每次调用 evaluate 创建一个新实例

【讨论】:

    【解决方案2】:
    1. 要创建一个 repl 服务器,您只需要这样做
    const repl = require('repl')
    repl.start({prompt: "> ", input: input_stream, output: output_stream");
    

    prompt 是一个字符串,它是提示,stream 是输入。 input_stream 需要是可读流,output_stream 需要是可写流。您可以阅读更多关于流 here 的信息。一旦流开始工作,你就可以做

    output_stream.on('data', (chunk) => {                                                                                                                                                            
       14   //whatever you do with the data                                                                                                                                                                     
       15 });                
    

    【讨论】:

    • hmmm... 一切看起来都不错,但只是一个小问题:在文档中我看到 getWritableStreamSomehow();。我应该如何创建流?没有从某个地方得到它。
    • 然后如何将字符串传递给readable stream。我的意思是这样的:readableStream.read("hello world")。那么这应该由repl解释。
    • 我链接了节点文档,你应该可以在那里得到你需要的其他东西
    • 要创建可写流,请执行const writable = new stream.Writable();
    猜你喜欢
    • 2016-12-23
    • 2019-10-30
    • 2021-01-04
    • 1970-01-01
    • 2017-06-28
    • 1970-01-01
    • 1970-01-01
    • 2018-07-01
    • 1970-01-01
    相关资源
    最近更新 更多