从node.js启动外部应用程序

我正在编写一个使用node.js访问本地文件系统的桌面Web应用程序。 我目前可以使用node.js打开并将文件复制到硬盘上的不同位置。 我还想要做的是允许用户使用与文件types关联的应用程序打开一个特定的文件。 换句话说,如果用户在Windows环境中select“myfile.doc”,它将用该文件启动MSWord。

我必须成为术语的受害者,因为除了与node.js进行通信的subprocess的产生之外,我一直没有find任何东西。 我只想为用户启动一个文件来查看,然后让他们决定如何处理它。

谢谢

你可以这样做

var cp = require("child_process"); cp.exec("document.docx"); // notice this without a callback.. process.exit(0); // exit this nodejs process 

这是不安全的想法,以确保该命令显示没有错误或任何不需要的输出

你应该添加回调参数child_process.exec(cmd,function(error,stdout,stderr){})

接下来你可以使用事件,所以你不会阻止脚本的执行,甚至不使用一个外部的node.js脚本来启动和处理从“master”脚本产生的进程的输出。

在下面的例子中,我使用了textmate“mate”命令来编辑文件hello.js,你可以用child_process.exec运行任何命令,但是你想打开文件的应用程序应该为你提供命令行选项。

 var exec = require('child_process').exec; exec('mate hello.js'); 
 var childProcess = require('child_process'); childProcess.exec('start Example.xlsx', function (err, stdout, stderr) { if (err) { console.error(err); return; } console.log(stdout); process.exit(0);// exit process once it is opened }) 

强调在哪里“退出”被称为。 这在Windows中正确执行。