20

I'm writing a desktop web app that uses node.js to access the local file system. I can currently use node.js to open and copy files to different places on the hard drive. What I would also like to do is allow the user to open a specific file using the application that is associated with the file type. In other words, if the user selects "myfile.doc" in a Windows environment, it will launch MSWord with that file.

I must be a victim of terminology, because I haven't been able to find anything but the spawning of child processes that communicate with node.js. I just want to launch a file for the user to view and then let them decided what to do with it.

Thanks

4

5 回答 5

24

你可以这样做

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 脚本来启动和处理您从“主”脚本生成的进程的输出。

于 2013-07-19T06:37:51.590 回答
7

在下面的示例中,我使用 textmate "mate" 命令来编辑文件 hello.js,您可以使用 child_process.exec 运行任何命令,但您要打开文件的应用程序应该为您提供命令行选项。

var exec = require('child_process').exec;
exec('mate hello.js');
于 2013-07-19T07:53:39.337 回答
4
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 中正确执行。

于 2016-12-01T13:03:59.997 回答
2

只需从命令提示符或以编程方式调用您的文件(任何带有扩展名的文件,包括 .exe):

var exec = require('child_process').exec;
exec('C:\\Users\\Path\\to\\File.js', function (err, stdout, stderr) {
    if (err) {
        throw err;
    }
})

如果你想运行一个没有扩展名的文件,你可以做几乎相同的事情,如下:

var exec = require('child_process').exec;
exec('start C:\\Users\\Path\\to\\File', function (err, stdout, stderr) {
    if (err) {
        throw err;
    }
})

如您所见,我们使用start打开文件,让窗口(或让我们选择的窗口)选择应用程序。

于 2018-09-26T02:11:01.393 回答
0

如果您更喜欢使用 async/await 模式打开文件,

const util = require('util');
const exec = util.promisify(require('child_process').exec);

async function openFile(path) {
  const { stdout, stderr, err } = await exec(path);
  if (err) {
    console.log(err);
    return;
  }
  process.exit(0);
}

openFile('D:\\Practice\\test.txt'); // enter your file location here
于 2022-03-01T18:19:17.320 回答