问题描述
我希望能够从终端中运行的node.js程序中打开Vim
,创建一些内容,保存并退出Vim
,然后抓取内容文件.
I would like to be able to open Vim
from node.js program running in the terminal, create some content, save and exit Vim
, and then grab the contents of the file.
我正在尝试做这样的事情:
I'm trying to do something like this:
filename = '/tmp/tmpfile-' + process.pid
editor = process.env['EDITOR'] ? 'vi'
spawn editor, [filename], (err, stdout, stderr) ->
text = fs.readFileSync filename
console.log text
然而,当它运行时,它只是挂起终端.
However, when this runs, it just hangs the terminal.
我也用 exec
尝试过,得到了相同的结果.
I've also tried it with exec
and got the same result.
更新:
由于此过程是通过在带有 readline 运行.我将最新版本的相关部分完全提取到一个文件中.全文如下:
This is complicated by the fact that this process is launched from a command typed at a prompt with readline running. I completely extracted the relevant parts of my latest version out to a file. Here is it in its entirety:
{spawn} = require 'child_process'
fs = require 'fs'
tty = require 'tty'
rl = require 'readline'
cli = rl.createInterface process.stdin, process.stdout, null
cli.prompt()
filename = '/tmp/tmpfile-' + process.pid
proc = spawn 'vim', [filename]
#cli.pause()
process.stdin.resume()
indata = (c) ->
proc.stdin.write c
process.stdin.on 'data', indata
proc.stdout.on 'data', (c) ->
process.stdout.write c
proc.on 'exit', () ->
tty.setRawMode false
process.stdin.removeListener 'data', indata
# Grab content from the temporary file and display it
text = fs.readFile filename, (err, data) ->
throw err if err?
console.log data.toString()
# Try to resume readline prompt
cli.prompt()
如上所示,它的工作方式是显示几秒钟的提示,然后启动到 Vim,但 TTY 搞砸了.我可以编辑和保存文件,并且内容打印正确.退出时也有一堆垃圾打印到终端,之后 Readline 功能被破坏(没有向上/向下箭头,没有 Tab 完成).
The way it works as show above, is that it shows a prompt for a couple of seconds, and then launches in to Vim, but the TTY is messed up. I can edit, and save the file, and the contents are printed correctly. There is a bunch of junk printed to terminal on exit as well, and Readline functionality is broken afterward (no Up/Down arrow, no Tab completion).
如果我取消注释 cli.pause()
行,那么 Vim 中的 TTY 是可以的,但我卡在插入模式中,并且 Esc
键不不行.如果我点击 Ctrl-C
它会退出子进程和父进程.
If I uncomment the cli.pause()
line, then the TTY is OK in Vim, but I'm stuck in insert mode, and the Esc
key doesn't work. If I hit Ctrl-C
it quits the child and parent process.
推荐答案
您可以从主进程继承 stdio.
You can inherit stdio from the main process.
const child_process = require('child_process')
var editor = process.env.EDITOR || 'vi';
var child = child_process.spawn(editor, ['/tmp/somefile.txt'], {
stdio: 'inherit'
});
child.on('exit', function (e, code) {
console.log("finished");
});
此处有更多选项:http://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options
这篇关于如何从 node.js 打开终端应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!