Execute OS specific script in node / Grunt - node.js

I have a Grunt task which executes .cmd file on the local machine to do its thing. I need to use this task on the CI server, which is a Linux machine. I have the relevant .sh (shell script for Linux) for that. I need a way to execute these two without changing my Gruntfile.
Currently I have to change my Gruntfile to make it work locally for windows and remote file uses .sh.
Any solution to do same is welcome. Detecting underlying OS? Or a way to call same command which internally calls the OS specific command?

You could take advantage of node's process.platform:
process.platform
What platform you're running on: 'darwin', 'freebsd', 'linux', 'sunos' or 'win32'
console.log('This platform is ' + process.platform);
Then within the code, optionally add the file extensions based on that:
if (process.platform === "win32") {
ext = ".cmd";
} else {
ext = ".sh";
}

Using grunt-shell or any other shell command tool, take advantage of the similarities between win and *nix shells, particularly ||. The first cmd will fail on *nix and fallback to sh:
shell: {
options: {
stderr: false,
failOnError: true
},
command: 'cmd command.cmd || sh command.sh'
}

Related

On Jenkins how can you detect if a server is Windows vs. Linux?

On Jenkins I'm using the Conditional BuildStep Plugin. Is there a way to have it run some build steps depending on whether or not the slave node it's running on is Windows vs. Linux?
You can use isUnix() function available in jenkins for identifying the OS type.
So you can use something like below inside your jenkinsfile under script block:-
if (isUnix()) {
sh 'ls -la'
} else {
bat 'dir'
}
To run commands only if the current server is Windows, use the Conditional BuildStep Plugin to check:
Strings match:
String 1: ${ENV,var="OS"}
String 2: Windows_NT
And to run commands only if the current server is Linux, check:
Strings match:
String 1: ${ENV,var="OS"}
String 2:
(Leaving String 2 blank.)

how to run windows service automatically using nodejs application? [duplicate]

Can any node.js experts tell me how I might configure node JS to autostart a server when my machine boots?
I'm on Windows
This isn't something to configure in node.js at all, this is purely OS responsibility (Windows in your case). The most reliable way to achieve this is through a Windows Service.
There's this super easy module that installs a node script as a windows service, it's called node-windows (npm, github, documentation). I've used before and worked like a charm.
var Service = require('node-windows').Service;
// Create a new service object
var svc = new Service({
name:'Hello World',
description: 'The nodejs.org example web server.',
script: 'C:\\path\\to\\helloworld.js'
});
// Listen for the "install" event, which indicates the
// process is available as a service.
svc.on('install',function(){
svc.start();
});
svc.install();
p.s.
I found the thing so useful that I built an even easier to use wrapper around it (npm, github).
Installing it:
npm install -g qckwinsvc
Installing your service:
> qckwinsvc
prompt: Service name: [name for your service]
prompt: Service description: [description for it]
prompt: Node script path: [path of your node script]
Service installed
Uninstalling your service:
> qckwinsvc --uninstall
prompt: Service name: [name of your service]
prompt: Node script path: [path of your node script]
Service stopped
Service uninstalled
If you are using Linux, macOS or Windows pm2 is your friend. It's a process manager that handle clusters very well.
You install it:
npm install -g pm2
Start a cluster of, for example, 3 processes:
pm2 start app.js -i 3
And make pm2 starts them at boot:
pm2 startup
It has an API, an even a monitor interface:
Go to github and read the instructions. It's easy to use and very handy. Best thing ever since forever.
If I'm not wrong, you can start your application using command line and thus also using a batch file. In that case it is not a very hard task to start it with Windows login.
You just create a batch file with the following content:
node C:\myapp.js
and save it with .bat extention. Here myapp.js is your app, which in this example is located in C: drive (spcify the path).
Now you can just throw the batch file in your startup folder which is located at C:\Users\%username%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
Just open it using %appdata% in run dailog box and locate to >Roaming>Microsoft>Windows>Start Menu>Programs>Startup
The batch file will be executed at login time and start your node application from cmd.
This can easily be done manually with the Windows Task Scheduler.
First, install forever.
Then, create a batch file that contains the following:
cd C:\path\to\project\root
call C:\Users\Username\AppData\Roaming\npm\forever.cmd start server.js
exit 0
Lastly, create a scheduled task that runs when you log on. This task should call the batch file.
I would recommend installing your node.js app as a Windows service, and then set the service to run at startup. That should make it a bit easier to control the startup action by using the Windows Services snapin rather than having to add or remove batch files in the Startup folder.
Another service-related question in Stackoverflow provided a couple of (apprently) really good options. Check out How to install node.js as a Windows Service. node-windows looks really promising to me. As an aside, I used similar tools for Java apps that needed to run as services. It made my life a whole lot easier. Hope this helps.
you should try this
npm forever
https://www.npmjs.com/package/forever
Use pm2 to start and run your nodejs processes on windows.
Be sure to read this github discussion of how to set up task scheduler to start pm2: https://github.com/Unitech/pm2/issues/1079
Here is another solution I wrote in C# to auto startup native node server or pm2 server on Windows.
I know there are multiple ways to achieve this as per solutions shared above. I haven't tried all of them but some third party services lack clarity around what are all tasks being run in the background. I have achieved this through a powershell script similar to the one mentioned as windows batch file. I have scheduled it using Windows Tasks Scheduler to run every minute. This has been quite efficient and transparent so far. The advantage I have here is that I am checking the process explicitly before starting it again. This wouldn't cause much overhead to the CPU on the server. Also you don't have to explicitly place the file into the startup folders.
function CheckNodeService ()
{
$node = Get-Process node -ErrorAction SilentlyContinue
if($node)
{
echo 'Node Running'
}
else
{
echo 'Node not Running'
Start-Process "C:\Program Files\nodejs\node.exe" -ArgumentList "app.js" -WorkingDirectory "E:\MyApplication"
echo 'Node started'
}
}
CheckNodeService
Simply use this, install, run and save current process list
https://www.npmjs.com/package/pm2-windows-startup
By my exp., after restart server, need to logon, in order to trigger the auto startup.
Need to create a batch file inside project folder.
Write this code in batch file
#echo off
start npm start
save batch file with myprojectname.bat
Go to run command and press window + R
Enter this command :- shell:common startup
Press ok then folder will be open.
Folder path like as C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp
You will be paste your myprojectname.bat file.
You can check also. Need to system restart.
Copied directly from this answer:
You could write a script in any language you want to automate this (even using nodejs) and then just install a shortcut to that script in the user's %appdata%\Microsoft\Windows\Start Menu\Programs\Startup folder

“bash read command” in nodejs

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

Golang Mac OSX build for Docker machine

I need to run Golang application on Docker machine.
I'm working on Mac OSX and Docker is working on top of Linux virtual machine, so binaries builded on Mac are not runnable on Docker.
I see two ways here:
cross-compile binaries on Mac for linux OS
copy project sources to docker, run 'go get' and 'go build' on it
First one is hard because of CGO (it is used in some imported libraries).
Second is very slow because of 'go get' operation.
Can you please tell me, which way is the most common in that situation? Or maybe I'm doing something wrong?
Here a solution to make cross-compile super easy even with CGO.
I stumbled upon it recently after wasting a lot of time getting a new windows build server to build my Go app.
Now I just compile it on my Mac and will create a Linux build server with it:
https://github.com/karalabe/xgo
Many thanks to Péter Szilágyi alias karalabe for this really great package!
How to use:
have Docker running
go get github.com/karalabe/xgo
xgo --targets=windows/amd64 ./
There are lots more options!
-- edit --
Almost 3 Years later I'm not using this any more, but my docker image to build my application in a linux based CD pipeline is still based on the docker images used in xgo.
I use the first approach. Here its a gulp task the build go code. If the production flag is set, it runs GOOS=linux CGO_ENABLED=0 go build instead go build. So the binary will work inside a docker container
gulp.task('server:build', function () {
var build;
let options = {
env: {
'PATH': process.env.PATH,
'GOPATH': process.env.GOPATH
}
}
if (argv.prod) {
options.env['GOOS'] = 'linux'
options.env['CGO_ENABLED'] = '0'
console.log("Compiling go binarie to run inside Docker container")
}
var output = argv.prod ? conf.paths.build + '/prod/bin' : conf.paths.build + '/dev/bin';
build = child.spawnSync('go', ['build', '-o', output, "src/backend/main.go"], options);
if (build.stderr.length) {
var lines = build.stderr.toString()
.split('\n').filter(function(line) {
return line.length
});
for (var l in lines)
util.log(util.colors.red(
'Error (go install): ' + lines[l]
));
notifier.notify({
title: 'Error (go install)',
message: lines
});
}
return build;
});
You could create a Docker container from the distinct OS you need for your executable, and map a volume to your src directory. Run the container and make the executable from within the container. You end up with a binary that you can run on the distinct OS.

How to execute shell script from hubot

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.

Resources