gpt4 book ai didi

node.js - 自定义 Node JS REPL 输入/输出流

转载 作者:行者123 更新时间:2023-12-04 07:40:16 24 4
gpt4 key购买 nike

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

为了让您更清楚地描述它,我正在处理 vscode plugin (github: source code)它提供了 REPL。就我而言,我有一个 vscode WebView从那里,我获得用户输入,然后我想将该输入传递给 Node REPL 并获取其输出并将其显示给用户。
那么,我将如何实现这一目标?如果您需要更多信息,请告诉我。提前致谢。
编辑 1:

const replServer = repl.start({
input: /* what should be here? */,
output: /* what should be here? */
});
编辑 2:
谁能解释一下 input 的用法是什么/ output上面例子中的参数?

最佳答案

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

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 的每次调用创建一个新实例

关于node.js - 自定义 Node JS REPL 输入/输出流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67518218/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com