简体   繁体   中英

How do use nodejs childprocess exec to run the unix diff command?

I need to use node to generate diffs of some files. I have tried the diff npm package , and while that works great it is much less performant than the version of diff you will find in /usr/bin/.

When I try to use exec to run the diff command it always errors.

var childProcess = require('child_process');

var cmd = "diff /path/to/file1.txt /path/to/file2.txt";
childProcess.exec(cmd, (error, stdout, stderr) => {
  if(error) {
    console.log(error);
  } else {
    console.log(stdout);
  }
});

The output:

{ [Error: Command failed: /bin/sh -c diff /path/to/file1.txt /path/to/file2.txt
]
  killed: false,
  code: 1,
  signal: null,
  cmd: '/bin/sh -c diff /path/to/file1.txt /path/to/file2.txt' }

If I run the command on the command line myself it works fine.

I've tried running /usr/bin/diff instead of just diff .

I've tried various different forms of quoting things.

Every other command I have tried, using the exact same files, has worked. cat , wc , etc.

Any thoughts?

Welp, I am answering my own question.

The diff command returns a failure exit code if it finds a difference. Therefore the console.log(stdout) call was never being reached. If I ignore the error, everything works.

var childProcess = require('child_process');
var cmd = "diff /path/to/file1.txt /path/to/file2.txt";
childProcess.exec(cmd, (error, stdout, stderr) => {
  console.log(stdout);
});

works like a charm.

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