Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

git commands in nodejs

I was wandering if someone know/got into a npm package to work with git commands. I have a nodejs project that I want to do the following commands:

  • git clone
  • git create branch
  • git pull request - from the created brach

I try some npm packages but without any success. any Help will be appreciated Thanks

like image 754
Boba Fett likes JS Avatar asked Apr 15 '15 15:04

Boba Fett likes JS


3 Answers

Using external package: You can use shelljs npm package

Without using external package: leveraging nodejs child_process module. Below is the implementation

1.exec_process.js

var exec = require('child_process').exec;

var result = function(command, cb){
    var child = exec(command, function(err, stdout, stderr){
        if(err != null){
            return cb(new Error(err), null);
        }else if(typeof(stderr) != "string"){
            return cb(new Error(stderr), null);
        }else{
            return cb(null, stdout);
        }
    });
}

exports.result = result;

2.temp.sh

#! /usr/bin/bash
pwd
git --version

3.app.js

var execProcess = require("./exec_process.js");
execProcess.result("sh temp.sh", function(err, response){
    if(!err){
        console.log(response);
    }else {
        console.log(err);
    }
});

To run the application you can try node app.js Output:

/root
git version 1.8.1.2

Similarly you can add any command in shell script file and run it using node. Demo and source code published in runnable.

Suggest checking git-extras it covers all the use cases of git via commandline.

like image 186
Samar Panda Avatar answered Nov 18 '22 19:11

Samar Panda


I don't think any of the modules support PRs, but for cloning / branch management, try gift:

https://www.npmjs.com/package/gift

This module appears to have the most git features. For PRs, I'd suggest creating an issue and/or contributing to this awesome module:

https://github.com/notatestuser/gift/issues

like image 30
Chris Tate Avatar answered Nov 18 '22 17:11

Chris Tate


While @samarpanda's answer was helpful, a slightly cleaner solution (from the nodejs documentation) is as follows:

const util = require('node:util');
const exec = util.promisify(require('node:child_process').exec);

async function lsExample() {
  const { stdout, stderr } = await exec('ls');
  console.log('stdout:', stdout);
  console.error('stderr:', stderr);
}
lsExample();
like image 1
Pratik K. Avatar answered Nov 18 '22 18:11

Pratik K.