How to concat multiple bash commands? - javascript

Having this bash_profile commands, trying to run backend and frontend server in one single alias command i.e ins
alias is='ivui && npm run start:backend'
alias ib='ivbe && npm run start:dev'
alias ins='ib && is'
is referring to a different project folder and it starts the server and ib is also referring to a different folder and server. Trying to concat both, but the first one only triggers and concat of && is not executed.
Concat npm helps in combining both servers from single project folder, but wondering how we can get this done using bash_profile? so that by executing just ins, it must start backend server first and frontend also.

The reason your double alias command (ib && is) does not work is because, as per man bash:
Aliases allow a string to be substituted for a word when it is used as
the first word of a simple command.
Stands to reason that if you run ib && is where both ib and is are aliases, it will only run ib.
With that out of the way, there is have a different and, I believe, better solution to your problem. You can use screen to run those 2 commands in the background and also, as a bonus, have the ability to watch their terminal output any time you want.
The idea is this: 1. Start a screen session; 2. Open two windows inside that session; 3. Run npm run start:backend in 1st window and run npm run start:dev in the second window.
Here is what you need:
screen -S Servers -t backend_window -A -d -m
screen -S Servers -X screen -t dev_window
This will start a screen session with backend_window and dev_window inside it. Now you just need to run your 2 commands inside those windows:
screen -S Servers -p backend_window -X stuff $'npm run start:backend\n'
screen -S Servers -p dev_window -X stuff $'npm run start:dev\n'
Now both your npm commands are running in the background at the same time. You can just put these 4 lines into your .bashrc file and it will launch on log in.
But the best part about this approach is you can visually see what's going on with those npm commands by attaching the screen and looking inside those windows. Just run:
screen -rx Servers
This will show you your first window by default. Let's split the screen and show both windows side by side:
Ctr-A + | <- will split the screen into 2 sections
Ctr-A + Tab <- will shit cursor to the new section
Ctr-A + " <- will show you your 2 windows, just pick the dev
All this will give you this view
Keep in mind that both your npm commands will continue to run even after you log out. To kill them, either attach the screen as described above and then Ctrl-C both processes. Or just run killall screen and they will just die.

You could create a function and add your aliases inside, for example,
stopdev () (
cd "$HOME/website" && {
make website_stop
ret=$?
make backend_stop && return $ret
}
)
This example also has a return code, and has a subshell called to run the function, so the filepath is not $HOME/website after the function is called.
More information on the following webpage,
https://unix.stackexchange.com/questions/266063/why-cant-i-call-two-aliases-with

Related

Is there a Git Bash command to deactivate all my active localhosts at once?

When creating a react app, I run these commands in my terminal:
npx create-react-app app-name
npm install
npm start
npm start allows me to view my project locally, but I accidently closed my terminal before running ctrl + c to end it. The browswer tab containing localhost 3000 (the npm start default host) has been closed for a while now, but my project can still be viewed there everytime I follow that link. Now everytime I run npm start it tells me that localhost 3000 is taken and I have to input another command and run it on localhost 3001. I've made this mistake a few times. I don't mind doing this, but it got me wondering if there is a global version of ctrl + c that will close all of these at once.
Firstly, I think you've had a misconceptions here: closing the browser tab will never end the server that you've started (i.e. the server npm start created).
For your question I think you can use the approach of killing a process based on the port they're occupying in this question:
Find (and kill) process locking port 3000 on Mac

Bot shuts down when putty window is closed

I created a discord bot and am now attempting to run it off an Ubuntu Machine.
I installed the folders of the bot and NodeJs, here is what I used to install NodeJS:
sudo apt-get install -y nodejs
Then I used cd to select the directory, and started my bot using node index.js
The bot started, however when I went to close the putty and keep it running on the VPS the bot shutdown. Here is what the directory looks like.
I think the problem is that when you start the app in the putty window, that process is linked to the window and gets terminated when that is closed.
To avoid that you can use a host service like screen, tmux, nohup, bg and so on...
If you want to know which is the best, try looking at this question from the askUbuntu Stack Exchange.
The key concept is that you open a new window using the tmux command (or screen, ...), then run your bot like you always do. When you want to leave but keep the process runing, you can detach the session with a key combination, that changes from service to service.
If you want to access that window again, you can run a command that will "restore" your session, like
tmux list-sessions
tmux attach-session -t 0
The NodeJS instance is terminated when putty is closed. You need something to keep the instance alive. Try:
PM2: http://pm2.keymetrics.io/
or,
Forever: https://github.com/foreverjs/forever#readme
Recommended though is to run the node instance as a service that can reboot on startup. Try looking at this:
https://stackoverflow.com/a/29042953/7739392
The shell runs in the foreground. This means any scripts you start there will end once you end your session. A simple solution would be to run your script in the background by adding the & after the call:
node index.js &
A better solution would be to create a service you can ask the service daemon to run for you. However, adding the & should get you what you want for now.
I recommend using one of these two node modules - ForeverJS or PM2. I'll show you how to quickly get started with ForeverJS but PM2 would be very similar.
You can easily install ForeverJS by typing the following in your terminal:
$ npm install forever -g
You may need to use SUDO depending on your user's privileges to get this working properly. It is NOT recommended to use it in production due to the security risks.
Once installed CD to your projects file directory and like you typed 'node index.js' you will do something similar with ForeverJS.
$ forever start index.js
Now when you exit the terminal your NodeJS application will remain as a running process.

Node's spawn() silently failing when called from a forever script scheduled on boot

This is kind of a doozy. This issue is most likely server related and so my first recourse was AskUbuntu over here.
I'm trying to have crontab or rc.local or init.d to start a forever script on boot. It attaches a server to a port I can ping with some information and have it run a headless browser for me.
That said, it seems that I'm unable to get a response from Node.js's spawn():
var CASPER_PATH = '/home/ubuntu/dev/casperjs/bin/casperjs'; // actual binary location, not a symlink
var SCRIPTS_PATH = '/home/custom_user/endpoints/server.js';
var fileName = req.body.source + '_' + req.body.type + '.coffee'; // looks like: mysource_my_scrape_type.coffee
var scrapeId = 'test_scrape';
var user = 'user123';
var pass = 'pass123';
if (fs.existsSync(SCRIPTS_PATH + fileName)) {
// If file is in place, spawn casperjs
var sP = spawn(CASPER_PATH,
[SCRIPTS_PATH + fileName, '--ssl-protocol=any', '--user='+user, '--scrapeId='+scrapeId, '--pass='+pass],
{ detached: true },
function (err, stdout, stderr) {});
sP.stdout.on('data', function(data) { console.log('stdout', data.toString('utf8')); });
sP.stderr.on('data', function(data) { console.log('stderr', data.toString('utf8')); });
sP.stdout.on('close', function(code) { console.log('close', code); });
res.send({ scheduled: true, key: scrapeId });
} else {
res.send({ scheduled: false, error: 'Incorrect source, type or the script is missing.' });
}
Before I added the PHANTOMJS_EXECUTABLE env to crontab or rc.local (doesnt seem to matter no matter the user level), stdout was useful:
stdout Fatal: [Errno 2] No such file or directory; did you install
phantomjs?
close false
Now that the environment var is there, there is no output at all after spawn().
Mind you, Casper starts up just fine if a user (of any privilege level) runs node/forever from bash.
How can I see why spawn() is failing?
This actually looks like a combo-bug between forever, spawn and casperjs (maybe phantomjs).
I was able to reproduce your problem, here is the full code of my test application.
You didn't show the full code, so my guess is that you have an express application and there is a special URL to run the casperjs script.
I build a simple app like this and it behaved this way:
Just start app with node script.js (script.js is the express app which runs the casperjs script in server.js) - it works OK, renders response and writes output from the child process event handlers to console
Start app as root with init.d script - doesn't work, once the child is spawned, no event handlers are triggered
Start app as root with init.d script, replace casperjs with echo - the same, doesn't work (see, here we have this problem with just forever running as root, spawn and echo)
Start app as a regular user (not root) with init.d, replace casperjs with 'echo' - it works, event handlers are triggered, here I was almost sure the issue is solved, but ... :(
Start app as a regular user (not root) with init.d, put back casperjs - it doesn't work again, event handlers are not triggered
The practical solution to this it to use pm2, I did this:
# install pm2
sudo npm install -g pm2
# generate init.d scripts for pm2
# this command will fail, but hint about the correct format with sudo
pm2 startup ubuntu
# do this in the folder with your application
pm2 start script.js
# remember your application
pm2 save
# also useful
# sudo service stop/start/restart pm2
# pm2 stop/start/restart script
Now pm2 will start automatically with the system and it will launch your application. Everything works, child process event handlers are triggered.
I did not understand your requirement completely. But i do have a similar situation with Ubuntu headless server.
what i am trying to do here is what i did
First, How is my crontab ?
crontab -u USER -e
#reboot exec sudo -u USER /bin/bash /home/USER/SHELL_SCRIPT.sh
See, here i am actually starting a shell script, and not a node server
Now inside this shell script(SHELL_SCRIPT.sh)
#! /bin/bash
# SHELL_SCRIPT.sh
cd /home/USER/
/home/USER/.npm-packages/bin/forever start -p /home/USER -a -d --watch false --pidFile /home/USER/forever.pid -l /home/USER/forever.log -o /home/USER/forever.out -e /home/USER/forever.err /home/USER/MY_NODE.js
and even inside my MY_NODE.js i follow absolute path, i just ignore $PATH, and don't use that.
Inside this node server, I do 100's of spawn
Now, i did this around 2 years back, so if you ask me why do this way, which i cannot answer

Where do npm background scripts go?

I have a program which relies on another program being run so I added this build command to my package.json file
"scripts": {
"start": "brunch watch --server",
"build": "coffee server/modules/events/book_server.coffee &"
}
so before I run my main script with npm start I run npm run-script build which makes my main script work, however when I quit my main script and then look for background processes with bg I get the message
> -bash: bg: current: no such job
so I decided to run npm run-script build again however the previous process must still have been running because I got the error message
events.js:66
throw arguments[1]; // Unhandled 'error' event
^
Error: listen EADDRINUSE
at errnoException (net.js:776:11)
at Server._listen2._connectionKey (net.js:917:26)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)
and when I tried to run my main program again I got the error
> TypeError: Cannot read property 'port' of null
My question is, where are these background scripts?
So far I have looked in all the obvious places including package.json's directory the directory for book_server.coffee and in node_modules but with no luck.
So the background processes go into the background just running inside the OS but not attached to your shell's tty. To find them, use jobs -l or the ps command with something like ps -ef. You can use grep to filter the output, but what you need to find is the process ID (PID) of your build process so you can stop it with kill <pid>. You may also want to read up on pgrep and pkill which are handy for this process.
Note that in your example you use bg when it's not appropriate. bg is for this sequence: 1. start a job in your shell's foreground, 2. suspend that job with CTRL-Z, 3. use bg to tell the shell "allow this job to continue executing, but detached from my tty in the background". (again, jobs is what you are looking for here).
For the bigger picture, there's no need or benefit of running that coffee command in the background as it is just a simple compliation step that should take on the order of a few milliseconds.
For an amazingly-detailed "reread every year" level of depth, check out The TTY demystified.

Ubuntu 8.04 Hardy and node.js upstart script

I am trying to write an upstart script for my ubuntu machine, which is version 8.04 "Hardy". I have followed the instructions on this site: upstart for node.js but it seems like these instructions are for a current version of ubuntu.
I noticed that the /etc/init directory does not exist on my machine, first I tried putting the script in the /etc/init.d directory and then I created the /etc/init dir and placed it there.
I will post my upstart script below (which is basically the same as from the website above with some path changes), but when I run start jobname, I just get an error "start: Unknown job: jobname". So then I changed the script around to a slimmed down version, posted below, and still I get the same result.
For now, I am using the 'nohup' command to run my node server but I would like a more permanent solution.
Please, any help?
SCRIPT 1:
description "node.js chat server"
author "iandev ith3"
# used to be: start on startup
# until we found some mounts weren't ready yet while booting:
start on started mountall
stop on shutdown
# Automatically Respawn:
respawn
respawn limit 99 5
script
# Not sure why $HOME is needed, but we found that it is:
export HOME="/root"
exec /root/local/node/bin/node /home/ian/chat.js >> /var/log/node.log 2>&1
end script
post-start script
# optionally put a script here that will notifiy you node has (re)started
# /root/bin/hoptoad.sh "node.js has started!"
end script
SCRIPT 2:
description "node.js chat server"
author "iandev ith3"
script
exec /root/local/node/bin/node /home/ian/chat.js >> /var/log/node.log 2>&1
end script
Just use Forever. https://github.com/indexzero/forever
From looking at the website you provided I'd say that the /etc/init was just a typo and it should be /etc/init.d/. Some things you may want to check:
executable flag on your scripts. With most versions of Ubuntu executable files show up green when running 'ls' from the command line. If you want to check if your file is executable run 'ls -l /etc/init.d/YOUR_SCRIPT' from the command line. You will see something like this:
-rwxr-xr-x 1 root root 1342 2010-09-16 10:13 YOUR_SCRIPT
The x's mean that it is executable.
To set the executable flag if it is not set, run chmod u+x YOUR_SCRIPT
I'm pretty sure for older versions of ubuntu you need to have the script in /etc/rc.d/rc3.d or /etc/rc3.d. What linux does is run through rc0.d to rc5.d and execute every script in there. From what it looks like, ubuntu is moving away from this to something simpler so if you have rc directories you may need to edit your script a little.
Anyway I think i'm getting a little over complicated here. Check your executable flag and if you have rc directories and we'll move on from there.
May not be the best thing to start a process with sudo, but here's what I have setup on my local pc:
#!upstart
description "node.js server"
author "alessio"
start on startup
stop on shutdown
script
export HOME="/ubuntu"
exec sudo -u ubuntu /usr/bin/node /home/ubuntu/www/test.js 2>&1 >> /var/log/node.log
end script
Hope this helps.

Categories