6

nodejs 子进程的正确用法(你应该忽视函数名)

 3 years ago
source link: https://blog.lilydjwg.me/2017/6/30/use-subprocess-in-nodejs-correctly.209987.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

nodejs 子进程的正确用法(你应该忽视函数名)

本文来自依云's Blog,转载请注明。

因为库太拙了,需要在 nodejs 里调用子进程来获取数据。然而看到 child_process 的文档真是头疼,这么多种启动子进程的方法直接推到人面前,也没个解释,命名也十分无用。只能一个个地查看详细说明来找到应该使用的那个……所以我整理了一下。

首先是同步创建子进程的那几个函数。会阻塞 nodejs 的主循环。无用。(要是写小脚本的话我直接上 shell 或者 Python 了,干嘛跟自己过不去呢。)

exec:调用 shell 来执行命令的。这部分跟「exec」这个词的 UNIX/C 语义刚好相反。

execFile:不调用 shell,直接执行命令。这命名不明所以。

fork:执行一个新的 nodejs 进程,并且建立一个专用的 IPC 通道。子进程除了 IPC 通道外与父进程无任何瓜葛!命名真是一如既往地误人子弟。默认使用与父进程相同的可执行文件(nodejs 版本),也可以另外指定。

spawn:相当于 Python 的 subprocess,可以指定是否使用 shell。默认不使用 shell。也支持 cwd 啊 env 啊 argv0 啊之类的参数。

结论:如果需要用 Python 的 subprocess.run / Popen 类似的功能,就使用 child_process.spawnexec 开头的那个函数似乎没啥大用,大概跟 subprocess 的 getoutput / check_call 之类的一样只是有一些预设而已吧。

发送到 Kindle


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK