javascriptjsondiff

How to add callback to method diff.structuredPatch?


Using library https://github.com/kpdecker/jsdiff and calling:

function structuredPatch(oldFileName: string, newFileName: string, oldStr: string, newStr: string, 
                         oldHeader: string, newHeader: string, options?: {context: number}): IUniDiff;

How do you pass a callback to it?


Solution

  • Prior to version 6.0.0, the callback option was only supported by the diffFoo family of functions, like diffChars, diffWords, etc., and not by patch-creation functions like structuredPatch. What you wanted to do was therefore simply not supported back in 2020 when you asked this question.

    However, I added support for using patch-creation functions asynchronously in v6.0.0, so if you upgrade to the latest version of jsdiff you can now invoke structuredPatch in async mode like this:

    structuredPatch(
      'oldfile', 'newfile',
      'foo\nbar\nbaz\n', 'foo\nbarcelona\nbaz\n',
      'header1', 'header2',
      {
        callback: (res) => {
          console.log(res);
          // Will log:
          // {
          //   oldFileName: 'oldfile', newFileName: 'newfile',
          //   oldHeader: 'header1', newHeader: 'header2',
          //   hunks: [{
          //     oldStart: 1, oldLines: 3, newStart: 1, newLines: 3,
          //     lines: [' foo', '-bar', '+barcelona', ' baz']
          //   }]
          // }
        }
    );