I wanna write a git hook scripts with nodejs which I'm good at. In bash files, I can get params like this:
#!/bin/bash
read local_ref local_sha remote_ref remote_sha
Is there any same command in nodejs?
#!/usr/bin/env node
"bash read function in nodejs"
here are some module which help u to write command
node-cmd
Simple commandline/terminal interface to allow you to run cli or bash style commands as if you were in the terminal.
shelljs
ShellJS is a portable (Windows/Linux/OS X) implementation of Unix shell commands on top of the Node.js API. You can use it to eliminate your shell script's dependency on Unix while still keeping its familiar and powerful commands. You can also install it globally so you can run it from outside Node projects - say goodbye to those gnarly Bash scripts!
https://www.npmjs.com/package/node-cmd
https://www.npmjs.com/package/shelljs
have a look at this code may help u
var cmd=require('node-cmd');
cmd.get(
git clone https://github.com/RIAEvangelist/node-cmd.git
cd node-cmd
ls
,
function(data){
console.log('the node-cmd cloned dir contains these files :\n\n',data)
}
);
have look on this module
// starting a new repo
require('simple-git')()
.init()
.add('./*')
.commit("first commit!")
.addRemote('origin', 'https://github.com/user/repo.git')
.push('origin', 'master');
// push with -u
require('simple-git')()
.add('./*')
.commit("first commit!")
.addRemote('origin', 'some-repo-url')
.push(['-u', 'origin', 'master'], function () {
// done.
});
https://www.npmjs.com/package/simple-git
Related
I am trying to build a shell script which can be called via a cronjob to trigger an npm nodejs application.
This is my start.sh shell script
#!/bin/bash
#!/usr/local/bin/npm
cd /home/lharby/sites/mysite
npm run start
If I cd to this folder and execute ./start.sh the command appears to run. (Path to bash and npm are both correct after checking which npm).
My cron job looks like this:
*/5 * * * * /home/lharby/sites/mysite/start.sh >> /home/lharby/sites/mysite/src/log/cron-errors.txt 2>&1
This is throwing an error and additionally I was lead to believe that using >> would append to the file, it seems to overwrite it each time.
My guess is that trying to run this command via cron it cannot access certain environment variables that are set up in my index.js
For example:
const config = {
access_token: process.env.NEXT_MASTODON_ACCESS_TOKEN,
client_key: process.env.NEXT_MASTODON_CLIENT_KEY,
client_secret: process.env.NEXT_MASTODON_CLIENT_SECRET,
timeout_ms: 60 * 1000,
api_url: 'https://botsin.space/api/v1/',
};
const M = new Mastodon(config);
I believe I see the same issue when I try to run node index.js from /home/sites/lharby/mysite/src/
As my package.json has this configuration:
"scripts": {
"start": "node ./src/index.js --experimental-modules",
"temp": "node ./src/temp.js --experimental-modules"
},
I was exploring looking at just trying to run the whole app passing in node index.js and passing in the argument flags but I need to be able to run the cron file invoking npm rather than node, as I guess that creates a wrapper and npm can access process.env variables.
From my cron-errors.txt file I am seeing this:
/home/lharby/sites/mysite/node_modules/mastodon-api/lib/mastodon.js:345
throw new Error('Mastodon config must include \'' + reqKey + '\' when using \'user_auth\'');
^
Error: Mastodon config must include 'access_token' when using 'user_auth'
at /home/lharby/sites/glyphbot/node_modules/mastodon-api/lib/mastodon.js:345:27
//
//
/home/lharby/sites/mysite/start.sh: line 4: npm: command not found
/bin/sh: 1: /home/sites/glyphbot/start.sh: not found
/bin/sh: 1: /home/sites/glyphbot/start.sh: not found
How can I ensure the crontab will invoke npm? I feel like I am doing everything correctly.
EDIT
My issues are:
How to run a node project using npm from a cron job?
Can the cronjob access environment variables from the npm command?
Should >> cron-errors.txt 2>&1 append the file rather than replace the content each time.
UPDATE 19.01.23
So I added exports for my variables to the .bashrc file. And when checking echo $NEXT_MASTODON_ACCESS_TOKEN I am seeing my string value.
Updated my .sh file so it now looks like this:
#!/bin/bash
node ./src/index.js --experimental-modules
And updated my cronjob to read this:
*/5 * * * * /home/lharby/sites/mysite/start.sh >> /home/lharby/sites/mysite/src/log/cron-errors.txt 2>&1
And I tried this also trying to bypass the shell script
*/5 * * * * /home/lharby/sites/mysite/src && /usr/local/bin/node index.js --experimental-modules >>/home/lharby/sites/mysite/src/log/cron-errors.txt 2>&1
It still failed with the same message being logged to the cron-errors.txt file.
However I am now able to run this command invoking node with argument flags (rather than using the npm command) So in the terminal I can type
node index.js --experimental-modules
As well as just running the .sh file I just don't understand why it is not passing this information to my cronjob.
I don't understand how if my code reads:
process.env.NEXT_MASTODON_ACCESS_TOKEN,
Will this get replaced or read by the bash export value instead?
Where are your environment variables being set up? It looks like your cron is at least running as expected, and your only problem is to get those env variables into the script correctly. My guess is that you need to use "export" (see bullet point 3)
I would debug this in a few different ways.
you should verify that it is the case that your index.js is not able to read your environment variables. I would recommend adding console.log(JSON.stringify(config, undefined, 2)) to check this.
you should verify that the SHELL has access to those variables before it runs the script. for this just run echo $NEXT_MASTODON_ACCESS_TOKEN (and similar for each variable) to verify if that is the case.
environment variables are a little funny. Assuming you set these values in your .bashrc with NEXT_MASTODON_ACCESS_TOKEN="whateverTheValueIs", just setting variables like this only affects your current process. In order for sub-processes to have the variable you need to export: export NEXT_MASTODON_ACCESS_TOKEN="insertValueHere"
Hope this helps!
Edit:
It's a little unclear what your current issues are, so it might be helpful if you bullet point each issue you are trying to solve
I'm working on a Node.js file to automatically create a new Github repo.
When I run curl -u 'BretCameron' https://api.github.com/user/repos -d '{"name":"test_repo"}' in the terminal, it asks me for my GitHub password and then creates the new repo.
But I can't get this to work in Node, even though the git commands in my sample code are working fine:
const { exec, execSync } = require('child_process');
function run(func) {
console.log(execSync(func).toString())
}
run('touch README.md');
run('git init');
run('git add README.md');
run('git commit -m "First commit"');
exec(`curl -u 'BretCameron' https://api.github.com/user/repos -d '{"name":"test_repo"}'`));
I have tried with the exec and execSync functions from the child_process module, as well as putting it into my helper function run. Can anyone offer some advice?
My requirement is to embed a terminal in my React-Electron app wherein all commands which I can run from bash can be run in the embedded terminal too.
Suppose I want to 'npm install' I want it to be possible through my embedded terminal too. Could anyone suggest possible solutions ?
I'm not exactly sure, but I bet you can create a interface with an text input, get the content from it, and use some function of NodeJS to run that content (witch should be a command). Then, just print the result on the screen.
You can use the exec function from "child_process" dependencie, like this.
const { exec } = require("child_process");
exec("ls");
For more details, you can check here: https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback
I am trying to merge branches into a main branch programmatically, using a node script. The first thing I tried was from Execute a command line binary with Node.js, which worked fine for executing terminal commands. But I encountered difficulties with changing the working directory. I wanted to change the working directory to the git repository, then run git commands from there. Executing cd ~/repo or cd /home/me/repo did not change the working directory at all and I could not find any way to change it other than using cd.
I then tried executing the git commands from the script's directory but pointed at my repo. I tried git --git-dir and git --work-tree but neither of those commands worked. The error was the same: fatal: Not a git repository (or any of the parent directories): .git I'm guessing this is because the directory where the script is running from is not a git repo.
So, I either want to send git commands to a directory other than the one I am running the script from, or I want a way to change the script's working directory. Preferably the latter. My full code and output is below:
import JiraData from './jiradata';
const jiraData = new JiraData();
const { exec } = require('child_process');
(async function () {
const cards = await jiraData.getCardsInTest();
let commands = ['cd /home/me/repo', 'pwd'];
let proceeding = true;
// for (const card of cards) {
// commands.push(`git merge origin/${card} --commit --no-edit`);
// }
for (const command of commands) {
if (proceeding) {
console.log(`Executing command "${command}"`);
exec(command, (err, stdout, stderr) => {
if (err) {
proceeding = false;
console.log(stderr);
return;
}
console.log(stdout);
})
}
}
})();
Output:
> ci#1.0.0 start /home/me/CI
> babel-node index.js --presets es2015,stage-2
Executing command "cd /home/me/repo"
Executing command "pwd"
/home/me/CI
Try instead with:
git -C /path/to/git/repo your_git_command
That will execute the git command in the context of your git repo /path/to/git/repo
I got around this problem by using ShellJS. ShellJS has a method .cd() which changes the directory and seems to stick.
I got my first hubot up and running, and wrote my first few scripts based on the existing examples. My existing workflow, which I would like to integrate with hubot, is essentially based on several shell scripts, each one of them performing one task. The task can be relatively complex (git/svn checkout, compiling code with gcc, and running it). How can I execute a bash script with hubot? I have seen this question, but it only addresses simple commands such as ls. I tried
build = spawn 'source', ['test.sh']
build.stdout.on 'data', (data) -> msg.send data.toString()
build.stderr.on 'data', (data) -> msg.send data.toString()
without any luck:
Hubot> execvp(): Permission denied
I checked the obvious things (-rwxr-xr-x permissions), and export HUBOT_LOG_LEVEL="debug".
I am running hubot with the same user that owns the bash scripts.
Thanks.
For reference: the answer was
build = spawn '/bin/bash', ['test.sh']
Dah
npm install hubot-script-shellcmd
is your doorway to the shell.