Skip to content

Instantly share code, notes, and snippets.

@lucthev
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucthev/f7096f85442ec448cb64 to your computer and use it in GitHub Desktop.
Save lucthev/f7096f85442ec448cb64 to your computer and use it in GitHub Desktop.
Example usage of the generic-diff module
one
-two
+twos
three
one
two
three
one
twos
three
#!/usr/bin/env node
'use strict'
var diff = require('generic-diff')
var fs = require('fs')
var os = require('os')
// Takes an array of edits containing “one or more” items each, and turns
// it into an array of edits with exactly one item per edit.
function flatten (changes) {
return changes.reduce(function (arr, edit) {
return arr.concat(edit.items.map(function (item) {
return {
item: item,
added: edit.added,
removed: edit.removed
}
}))
}, [])
}
// Read two files passed in on the command line, splitting them at
// newlines.
var before = process.argv[2]
before = fs.readFileSync(before, { encoding: 'utf-8' })
before = before.split(/\r?\n/)
var after = process.argv[3]
after = fs.readFileSync(after, { encoding: 'utf-8' })
after = after.split(/\r?\n/)
// Perform the diff. Prepend added lines with a '+', removed lines with
// a '-', and unchanged lines with a space.
var changes = flatten(diff(before, after))
changes = changes.map(function (edit) {
var pre = ' '
if (edit.added) {
pre = '+'
} else if (edit.removed) {
pre = '-'
}
return pre + edit.item
})
// That’s it!
console.log(changes.join(os.EOL))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment