Get changed files in a git repository with Node.js

This snippet will help you retrieve the list of the currently changed files in a git repository using Node.js.

ยท1 min read

It can be useful to retrieve the list of the currently changed files in a git repository.

For example, you might want to run a script only if a specific file has been changed, such as when indexing a search engine with new content that has been added to a repository: we use this technique in this website when a new post is added or an existing one is updated.

To write the script, we will use:

  1. the git diff command
  2. and Node.js
import { execSync } from 'child_process'; function getChangedFiles(extension: string = '') { const extensionFilter = extension ? `-- '***.${extension}'` : ''; const command = `git diff HEAD^ HEAD --name-only ${extensionFilter}`; const diffOutput = execSync().toString(command); return diffOutput.toString().split('\n').filter(Boolean); }

The getChangedFiles function takes an optional extension parameter that will filter out the files that do not have the given extension.

For example, if we want to retrieve the list of the changed files that have a .mdx extension, we can call the function like this:

const changedFiles = getChangedFiles('mdx');

The getChangedFiles function will return an array of the changed files whose path starts from the current directory.

That's it! Hope you found this snippet useful. Ciao!