我正在编写一个桌面Web应用程序,使用node.js访问本地文件系统。 我目前可以使用node.js打开和复制文件到硬盘上的不同位置。 我还想允许用户使用与文件类型关联的应用程序打开特定文件。 换句话说,如果用户在Windows环境中选择“myfile.doc”,它将启动带有该文件的MSWord。
我一直被术语所困扰,因为除了与node.js通信的子进程外,我什么也没找到。 我只想为用户启动一个文件供他们查看,然后让他们决定如何处理它。
谢谢
我正在编写一个桌面Web应用程序,使用node.js访问本地文件系统。 我目前可以使用node.js打开和复制文件到硬盘上的不同位置。 我还想允许用户使用与文件类型关联的应用程序打开特定文件。 换句话说,如果用户在Windows环境中选择“myfile.doc”,它将启动带有该文件的MSWord。
我一直被术语所困扰,因为除了与node.js通信的子进程外,我什么也没找到。 我只想为用户启动一个文件供他们查看,然后让他们决定如何处理它。
谢谢
你可以做到这件事
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脚本启动和处理从“主”脚本中生成的进程的输出。
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
})
重点在于'exit'被调用的位置。这在Windows系统中可以正确执行。
只需从命令提示符或程序中调用您的文件(任何带扩展名的文件,包括.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
打开文件,让Windows选择应用程序(或者Windows允许我们选择)。如果您喜欢使用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