Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do yoy recursively compare two directories in node

Tags:

git

node.js

Id like to perform a comparison of two directories and all files within sub folders. The folder structure will be the same for both directories the files may be different. Call them directory A and directory B.

From that id like to create a directory C and directory D. All files in B that are newer than A or that are not found in A should copy over to C. Files missing from B that are found in A should be copied to directory D.

Id like to use node and either a library or run some other CLI tool like git perhaps that can do what I described without too much effort.

What would be some good approaches to accomplish this?

like image 753
Joseph U. Avatar asked Jul 27 '17 03:07

Joseph U.


People also ask

Is there a way to compare two directories?

WinMerge is a tool that allows you to compare the contents of two directories. You can see if there are any missing files or if any of the backed-up files are different from the originals. This guide will walk you through installing and using WinMerge to compare the files in two folders.


2 Answers

Get the list of filenames of both directories as two arrays, then find the difference between them.

const _ = require('lodash');
const fs = require('fs');

const aFiles = fs.readdirSync('/path/to/A');
const bFiles = fs.readdirSync('/path/to/B');

_.difference(aFiles, bFiles).forEach(v => {
    // Files missing from B that are found in A should be copied to directory D
    // Move file v to directory D
});


_.difference(bFiles, aFiles).forEach(v => {
    // Files missing from A that are found in B should be copied to directory C
    // Move file v to directory C
});
like image 112
Chris Lam Avatar answered Nov 14 '22 23:11

Chris Lam


There's an npm package for this called dir-compare:

const dircompare = require('dir-compare');

const options = { compareSize: true };
const path1 = "dir1";
const path2 = "dir2";

const res = dircompare.compareSync(path1, path2, options)
console.log(res);
like image 40
Paul Razvan Berg Avatar answered Nov 14 '22 21:11

Paul Razvan Berg