简体   繁体   中英

How to run a windows batch file with node js

What I have tried: Using Node JS Child Process API to spawn the bat file in my projectfolder. But I couldnt get it running.

 projectfolder/
 ├──src/                       
 |   ├──app                 
 |        ├──home  
 |             ├──home.component.ts 
 |── my.bat (File Type: Bat shortcut)     

home.component.ts

    let spawn = require('child_process').spawn,
      ls = spawn('cmd.exe', ['/c', 'my.bat']);

    ls.stdout.on('data', function (data) {
      console.log('stdout: ' + data);
    });

    ls.stderr.on('data', function (data) {
      console.log('stderr: ' + data);
    });

    ls.on('exit', function (code) {
      console.log('child process exited with code ' + code);
    });

Error

stderr: 'my.bat' is not recognized as an internal or external command, operable program or batch file.

home.component.ts?71c4:159 child process exited with code 1

I have also tried

const exec = require('child_process').execFile;
    exec('my.bat', function (err, data) {
      console.log(err);
      console.log(data);
    });

with error

Error: spawn my.bat ENOENT at exports._errnoException (util.js:1050) at Process.ChildProcess._handle.onexit (internal/child_process.js:193) at onErrorNT (internal/child_process.js:367) at _combinedTickCallback (internal/process/next_tick.js:80) at process._tickCallback (internal/process/next_tick.js:104)

Update: I found the issue.

My File Type is a Bat shortcut

The above code only works for Windows Batch File , but not a shortcut

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM