Search code examples
javascriptnode.jschild-process

diff is not working in execSync producing error when file doesnot match


diff command gives error when my files does not match const exec_options = { cwd : "/home" , encoding : 'utf8', }

    let {stdout,stderr,err} =    execSync(`diff  output.txt answer.txt` , exec_options);
if(err){
    console.log(err);
}
console.log(stdout);

The above command gives desired result with exec and in terminal but does not work using exec sync


Solution

  • execSync returns string or buffer

    Your code should be..

    const stdout = execSync(`diff output.txt answer.txt` , exec_options);
    console.log(stdout.toString());
    

    if you want to configure stderr and stdout, uses spawnSync

    Why execSync is fail ?

    https://askubuntu.com/questions/698784/exit-code-of-diff

    because, diff returns non-zero when something is different.

    and execSync determines normal termination only when the value is 0.

    so if something is different, diff returns 1, and execSync guess command failed.

    actually we get that message.

      try {
        let stdout = execSync(`diff a b`, exec_options)
        console.log(stdout.toString())
      } catch (e: any) {
        console.log(e.message)
        console.log(e.stdout.toString())
      }
    
    Command failed: diff a b
    2c2
    < a
    ---
    > b
    

    some test

      try {
        const command = 'diff a c'
        console.log(`command : ${command}`)
        let stdout = execSync(command, exec_options)
        console.log(stdout.toString())
      } catch (e: any) {
        console.log('prev')
        if (e.status === 1) {
          console.log('diff result:')
          console.log(e.stdout.toString())
          console.log(e.stderr.toString())
        } else {
          console.log('error message : ')
          console.log(e.stdout.toString())
          console.log(e.stderr.toString())
        }
      }
    

    will print

    command : diff a a // in same case
                       // nothing returns
    ~~~~~~~~
    command : diff a b // in diff case
    prev
    diff result:
    2c2                // e.stdout exist
    < a
    ---
    > b
                       // e.stderr doesn't exist
    ~~~~~~~~
    command : diff a c // in fail case
    diff: c: No such file or directory // print at execSync.
    prev
    error message : 
                       // e.stdout doesn't exist
    diff: c: No such file or directory // e.stderr exist