Search code examples
node.jsgitgithooks

How to create git hooks in Windows with Node.js?


I have been following this guide on how to use Node.js to script git hooks. However, the guide is using a Unix based system whilst I am running on a Windows machine.

I have also found this guide on running git hooks on a Windows machine, but it is not using Node.js

  • I am running a pre-install script in my package.json file to set a custom git hooks location.
  • I am using VSCode as my editor and would like the git hooks to run when I use the UI for commits etc. However I am using command line initially to try and get the hooks to fire.

package.json excerpt

  "scripts": {
    "preinstall": "git config core.hooksPath ./git.hooks"
  },

In my git.hooks folder I have a pre-commit.js file.

I have updated the first line to reflect the fact I'd like to execute the script running Node.js

pre-commit.js

#!C:/Program\ Files/nodejs/node.exe

console.log('Hello world!');

process.exit(1);

If I run this script directly I get a Microsoft JScript compilation error - Invalid character on line 1 char 1.

If I do a commit, I get no errors but nothing happens.

Can anyone guide me through the process of creating a Node.js hook in Windows. I would rather create one myself than use a package.


Solution

    1. Name the hook exactly pre-commit, without .js.

    2. Change the first line to #!/usr/bin/env node. But make sure that C:/Program\ Files/nodejs/node.exe has been added to the environment variable PATH.

    3. Place it in <repo>/.git/hooks.

    4. Make it executable. In git-bash, run chmod a+x <repo>/.git/hooks/pre-commit. (This is actually not necessary on Windows.)

    Now it should work as expected.