Over a million developers have joined DZone.

How to Build a GitHub Webhook with Node.js

DZone's Guide to

How to Build a GitHub Webhook with Node.js

· Web Dev Zone ·
Free Resource

Building real-time chat? Enroll in a Free Course on Mobile Chat Development. 

webhook image

GitHub Webhooks

Every GitHub repository can easily communicate with a web server whenever the repository is pushed. This communication is called a webhook.  Webhooks are used for many reasons, including updating an external issue tracker, creating a backup mirror or triggering a continuous integration build.

Click here for information on how to set up webhooks on GitHub.  For this tutorial let’s set the webhook to port ’8082′, with URL ‘pushchanges’ and secret ’123456′.  You will obtain a GitHub personal access token as described in GitHub.

In this tutorial, you will learn how to listen to push events on GitHub through the webhook,and then fetch modified content with Node.js.

The Webhook

The first thing you will do is listen to push events by using node-github-hook:

    var githubhook = require('githubhook');
    // configure listener for github changes
    var github = githubhook({/* options */
		   host: "",
       port: 8082,
       path: "/pushchanges",
       secret: "123456"  

    // listen to push on github on branch master
    github.on('push', function (repo, ref, data) {
		  var branchName = _s.strRightBack(ref, "/");
		  var fullNameRepository = data.repository.full_name;
		  var removedFilesArray = data["head_commit"]["removed"];
		  var addedFilesArray = data["head_commit"]["added"];
		  var modifiedFilesArray = data["head_commit"]["modified"];

    // listen to github push

Fetching Content

You will use octonode to fetch file contents and return the contents as a Node.js ‘Buffer’ in the callback.

(Note: In this example Underscore.string is used to extract the branch, after the rightmost slash.)

    var octonode = require('octonode');
    var _s = require('underscore.string'); 
    var gitHubAccessToken = "xxxxxx";

    function fetchFileFromGitHub(gitHubAccessToken, repoFullName, 
      branchName, filePath, callback) {

      var client = octonode.client(gitHubAccessToken);  
	    var repo = client.repo(repoFullName);

	    repo.contents(filePath, branchName, function (err, body) {		  
		    if (err){
		  	    var buffer = new Buffer(body["content"], 'base64');	 

Build your Angular app and connect it to any database with Backand today. – Get started now.

Power realtime chat, IoT and messaging apps at scale. Pubsub realtime messaging, functions, chat, presence, push, notifications, blocks catalog and more.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}