0

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.

1 Answer 1

6
  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.

Sign up to request clarification or add additional context in comments.

2 Comments

This works, even in Powershell. I'm not sure I understand why though? How does Powershell interpret that first line?
@Antfish It's not entirely clear to me. I think it's interpreted in git bash environment in the end, so it doesn't matter if you are running git commit in cmd, powershell, git bash or gui tools.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.