96

I've installed and is running a node.js server on osx. I've dled a chat module and is happily running it. I've altered some pieces and need to restart the server to see the effects.

I only know how to restart by closing the terminal window and then reopneing it and then running node chatdemo.js again.

Any way to restart without closing terminal?

Thanks.

1

10 Answers 10

120

If it's just running (not a daemon) then just use Ctrl-C.

If it's daemonized then you could try:

$ ps aux | grep node
you   PID  1.5  0.2  44172  8260 pts/2    S    15:25   0:00 node app.js
$ kill -2 PID

Where PID is replaced by the number in the output of ps.

Sign up to request clarification or add additional context in comments.

3 Comments

You could also use "killall -2 node", which has the same effect.
Don't want/need to kill all node processes. If I have some node repl's open I'll be an unhappy camper after that line :)
side note: start a node daemon by nohup node server.js &
65

During development the best way to restart server for seeing changes made is to use nodemon

npm install nodemon -g

nodemon [your app name]

nodemon will watch the files in the directory that nodemon was started, and if they change, it will automatically restart your node application.

Check nodemon git repo: https://github.com/remy/nodemon

3 Comments

I didn´t know about this module, it´s something very useful, reminds me my django app. thanks.
Fantastic suggestion. Very efficient for development to test code quickly.
ok thanks, how can we configure eclipse to use nodemon instead of node..?
18

I had the same problem and then wrote this shell script which kills all of the existing node processes:

#!/bin/bash
echo "The following node processes were found:"
ps aux | grep " node " | grep -v grep
nodepids=$(ps aux | grep " node " | grep -v grep | cut -c10-15)

echo "OK, so we will stop these process/es now..."

for nodepid in ${nodepids[@]}
do
echo "Stopping PID :"$nodepid
kill -9 $nodepid
done
echo "Done"

After this is saved as a shell script (xxx.sh) file you might want to add it to your PATH as described here.

(Please note that this will kill all of the processes with " node " in it's name except grep's own, so I guess in some cases it may also kill some other processes with a similar name)

2 Comments

I'm on mac osx I had to use cut -c17-20
Isn't this exactly what pkill node is for?
16

In this case you are restarting your node.js server often because it's in active development and you are making changes all the time. There is a great hot reload script that will handle this for you by watching all your .js files and restarting your node.js server if any of those files have changed. Just the ticket for rapid development and test.

The script and explanation on how to use it are at here at Draco Blue.

1 Comment

FYI there are now several node modules dedicated to just that, take a look at the Node modules Wiki page.
9

To say "nodemon" would answer the question.

But on how only to kill (all) node demon(s), the following works for me:

pkill -HUP node

Comments

7

I understand that my comment relate with windows, but may be someone be useful. For win run in cmd:

wmic process  where "commandline like '%my_app.js%' AND name='node.exe' " CALL Terminate

then you can run your app again:

node my_app.js

Also you can use it in batch file, with escape quotes:

wmic process  where "commandline like '%%my_app.js%%' AND name='node.exe' " CALL Terminate
node my_app.js

1 Comment

Very handy! Great idea.
4

If I am just run the node app from console (not using forever etc) I use control + C, not sure if OSX has the same key combination to terminate but much faster than finding the process id and killing it, you could also add the following code to the chat app you are using and then type 'exit' in the console whenever you want to close down the app.

process.stdin.resume();
process.stdin.setEncoding('utf8');

process.stdin.on('data', function(data) {
  if (data == 'exit\n') process.exit();
});

Comments

3

Using "kill -9 [PID]" or "killall -9 node" worked for me where "kill -2 [PID]" did not work.

1 Comment

No, don't go kill -9. It does not let the process cleanly finish, will leave descriptors orphaned, and usually not needed. A vanilla kill is enough, if not, kill -INT will be enough. Don't go kill -9 unless really needed, and most of the time, it isn't.
1

At first open terminal/command line then go to your project directory, now install nodemon by using command npm install nodemon --save-dev this command will make sure it saved as developer dependency. If you are working with expressjs then in your package file it will look like

{
  "name": "expressjs-app",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "cookie-parser": "~1.4.4",
    "debug": "~2.6.9",
    "express": "~4.16.1",
    "http-errors": "~1.6.3",
    "morgan": "~1.9.1",
    "pug": "^2.0.4"
  },
  "devDependencies": {
    "nodemon": "^2.0.3"
  }
}

now modify the "start" value in your package.json file, for production we will use the exsiting value but for development will use nodemon to track the changes in source file without restarting server. There for new value for start is "start": "if [[$NODE_ENV=='production']]; then node ./bin/www; else nodemon ./bin/www; fi"

final package.json file will look like

{
  "name": "expressjs-app",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "if [[$NODE_ENV=='production']]; then node ./bin/www; else nodemon ./bin/www; fi"
  },
  "dependencies": {
    "cookie-parser": "~1.4.4",
    "debug": "~2.6.9",
    "express": "~4.16.1",
    "http-errors": "~1.6.3",
    "morgan": "~1.9.1",
    "pug": "^2.0.4"
  },
  "devDependencies": {
    "nodemon": "^2.0.3"
  }
}

to uninstall nodemon jusy simply run the command npm uninstall nodemon

Comments

0

A super handy feature i use with just about every server i write

place it in your main file somewhere and this allows you to

  • restart/reload by pressing r

  • quit by pressing escape - no more squishing that pinky

;

(function restart(){

      if(!process.stdin.isTTY)return;
      
      process.stdout.setEncoding('utf8');
      process.stdin.setRawMode(true);
      process.stdin.resume();
      process.stdin.setEncoding('utf8');
      
      var ctrlc   = '\u0003';
      var esc     = String.fromCharCode(27);
      process.stdin.on('data',keypressed);

      function keypressed(key){
      
            if(key===ctrlc || key===esc)process.exit();
            if(key==='r'){
                  process.stdin.off('data',keypressed);
                  server.close(()=>{
                  
                      var js    = fs.readFileSync(__filename);
                      var fn    = Function('require','__filename','__dirname',js);
                      fn(require,__filename,__dirname);
                      
                  });
            }
            
      }//keypressed
      
})();

if your server is not in the variable named server, you'll have to change that to whatever it is called

you can extend it further by adding things like

    if(key===' '){
          process.stdout.write('\x1Bc');
          //process.stdout.write('\033c');
          console.clear();
          console.log('---   clear   ---');
    }
    
    if(key==='-'){
          console.log('---   ...    ---');
    }

then while the server is running you can

  • tap space to clear the screen

  • tap - to insert a marker

handy when you have logs being printed to the console

best of all its completely contained within your own code, you dont have to modify anything, download anything and the server only restarts when you tell it to

hope this helps other people as much as it helps me

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.