문제

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

도움이 되었습니까?

해결책

you can do this

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

it not safe thought, to ensure that the command show no errors or any undesired output

you should add the callback parameter child_process.exec(cmd,function(error,stdout,stderr){})

and next you can work with events so you won't block execution of script or even make use of a external node.js script that launches and handles outputs from processes which you spawn from a "master" script.

다른 팁

In below example I have used textmate "mate" command to edit file hello.js, you can run any command with child_process.exec but the application you want to open file in should provide you with command line options.

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
})

Emphasis on where 'exit' is called. This executes properly in windows.

Simply call your file (any file with extension, including .exe) from the command promp, or programmatically:

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

If you want to run a file without extension, you can do almost the same, as follow:

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

As you can see, we use start to open the File, letting windows (or windows letting us) choose an application.

If you prefer opening a file with async/await pattern,

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top