57

EDIT After further testing, I have found that this is happening with both gulp and grunt on this app and on the default install of mean.js. I'm running this locally on a Mac. When I running either app using "node server.js" they don't crash.

I'm using a MEAN stack with grunt-nodemon and node is crashing when an express URL is accessed. It isn't always consistent though. Sometimes it works, sometimes node crashes right when the URL is hit retiring no data, and other times I get a response and node crashed immediately after.

Browser console response:

http://localhost:8000/api/users net::ERR_CONNECTION_REFUSED

Terminal output:

Mongoose: users.insert({ firstname: 'mike', lastname: 'jones', email:'mike@gmail.com', role: 'admin', password: 'mike', _id: ObjectId("57485c16fc11894b96c28057"), created: new Date("Fri, 27 May 2016 14:39:18 GMT"), __v: 0 })   
user.save success
node crash
[nodemon] app crashed - waiting for file changes before starting...

In this case, the POST request went through, the user was added, then node crashed, but sometimes it crashes before a successful POST. Node also occasionally crashes on the GET request.

gruntfile.js:

module.exports = function(grunt) {
    // Load grunt tasks automatically
    require('load-grunt-tasks')(grunt);

    var pkg = grunt.file.readJSON('package.json');

    var options = {
        paths: {
            app: 'app',
            assets: 'app/assets',
            dist: 'app/dist',
            distAssets: 'app/dist/assets',
            html: 'app/html',
            htmlTmp: '.tmp/htmlsnapshot',
            htmlAssets: 'app/html/assets',
            index: 'app/dist/index.html',
            indexDev: 'app/index.html',
            indexTmp: '.tmp/html/index.html'
        },
        pkg: pkg,
        env: {
            test: {
                NODE_ENV: 'test'
            },
            dev: {
                NODE_ENV: 'development'
            },
            prod: {
                NODE_ENV: 'production'
            }
        }
    };

    // Load grunt configurations automatically
    var configs = require('load-grunt-configs')(grunt, options);

    // Define the configuration for all the tasks
    grunt.initConfig(configs);

    // Connect to the MongoDB instance and load the models
    grunt.task.registerTask('mongoose', 'Task that connects to the MongoDB instance and loads the application models.', function () {
        // Get the callback
        var done = this.async();

        // Use mongoose configuration
        var mongoose = require('./config/lib/mongoose.js');

        // Connect to database
        mongoose.connect(function (db) {
            done();
        });
    });

    grunt.registerTask('bumper', ['bump-only']);
    grunt.registerTask('css', ['sass']);
    grunt.registerTask('default', [
        'sass',
        'copy:dev',
        'nodemon',
        'concurrent:dev',
        'watch',
        'mongoose'
    ]);

    grunt.registerTask('shared', [
        'clean:demo',
        'copy:demo',
        'sass',
        'ngconstant',
        'useminPrepare',
        'concat:generated',
        'cssmin:generated',
        'uglify:generated',
        'filerev',
        'usemin',
        'imagemin',
        'usebanner'
    ]);

    grunt.registerTask('demo', [
        'shared',
        'copy:postusemin',
        'grep:demo'
    ]);

    grunt.registerTask('dist', [
        'shared',
        'copy:postusemin',
        'copy:dist',
        'grep:dist',
        'compress',
        'copy:postusemin',
        'grep:demo',
    ]);

    grunt.loadNpmTasks('grunt-forever');

};

default.js

module.exports.tasks = {
    // version update
    bump: {
        options: {
            files: ['package.json', 'bower.json'],
            pushTo: 'origin'
        }
    },

    // application constants
    ngconstant: {
        options: {
            dest: '<%= paths.assets %>/js/app.constants.js',
            name: 'app.constants',
        }
    },

    // remove all bs from css
    cssmin: {
        options: {
            keepSpecialComments: 0
        }
    },
    markdown: {
        all: {
            files: [
                {
                    src: 'README.md',
                    dest: '<%= paths.assets %>/tpl/documentation.html'
                }
            ],
            options: {
                template: '<%= paths.assets %>/tpl/_documentation_template.html',
            }
        }
    }
};

dev.js:

var _ = require('lodash'),
defaultAssets = require('./assets/default'),
testAssets = require('./assets/test'),
testConfig = require('./env/test'),
fs = require('fs'),
path = require('path');

module.exports.tasks = {
    // copy files to correct folders
    copy: {
        dev: {
            files: [
                { expand: true, src: '**', cwd: '<%= paths.app %>/bower_components/font-awesome/fonts',                    dest: '<%= paths.assets %>/fonts' },
                { expand: true, src: '**', cwd: '<%= paths.app %>/bower_components/material-design-iconic-font/fonts',     dest: '<%= paths.assets %>/fonts' },
                { expand: true, src: '**', cwd: '<%= paths.app %>/bower_components/roboto-fontface/fonts',                 dest: '<%= paths.assets %>/fonts' },
                { expand: true, src: '**', cwd: '<%= paths.app %>/bower_components/weather-icons/font',                    dest: '<%= paths.assets %>/fonts' },
                { expand: true, src: '**', cwd: '<%= paths.app %>/bower_components/bootstrap-sass/assets/fonts/bootstrap', dest: '<%= paths.assets %>/fonts' }
            ]
        }
    },

    // watch for changes during development
    watch: {
        js: {
            files: ['Gruntfile.js', '<%= paths.assets %>/js/**/*.js'],
            tasks: ['jshint'],
            options: {
                livereload: true
            }
        },
        css: {
            files: [
                '<%= paths.assets %>/css/**/*.scss'
            ],
            tasks: ['sass'],
            options: {
                livereload: true
            }
        },
        markdown: {
            files: [
                'README.md'
            ],
            tasks: ['markdown']
        },
        tasks:  [ 'express:dev' ],
    },

    // debug while developing
    jshint: {
        all: ['Gruntfile.js', '<%= paths.assets %>/js/**/*.js']
    },
    concurrent: {
        dev: {
            tasks: ['nodemon', 'node-inspector', 'watch'],
            options: {
                logConcurrentOutput: true
            }
        }
    },
    nodemon: {
        dev: {
            script: 'server.js',
            options: {
                nodeArgs: ['--debug'],
                ext: 'js,html',
                callback: function (nodemon) {

                    nodemon.on('crash', function (event) {
                        console.log(event);
                    });


                },
                watch: _.union(defaultAssets.server.gruntConfig, defaultAssets.server.views, defaultAssets.server.allJS, defaultAssets.server.config)
            }
        }
    },
    forever: {
        server1: {
            options: {
                index: 'server.js',
                //logDir: 'logs'
            }
        }
    }
};

Angular controller function:

  $scope.addUser = function(){

      var user = {
          firstname: $scope.firstname,
          lastname: $scope.lastname,
          email: $scope.email,
          role: $scope.role.selected,
          password: $scope.password
      };

      $http.post('/api/userAdd', user ).then(function successCallback(response) {
          $location.path('/users');
      }, function errorCallback(response) {
          console.log('error addding user');
          console.log(response);
      });
  };

Express route:

User = require('../models/user.js');

module.exports = function (app) {

    app.get('/api/users', function (req, res) {

        User.find({}, function (err, users) {
            if ( err ) {
                res.send({
                    message : 'error finding users',
                    success: false
                });
            } else {
                res.json(users);
            }
        });

    });

    app.get('/api/users', function (req, res) {
        User.find({fields: {}}, function (err, docs) {
            res.json(docs);
        });
    });

    app.post('/api/userAdd', function (req, res) {

        var user = new User(req.body);

        user.save( function( err, user ){

            if (err){
                console.log('user.save error');
                console.log(err);
                res.send({
                    success: false
                });
            } else {
                console.log('user.save success');
                res.send({
                    success: true
                });
            }
        });

    });

};

I'm also testing with Chromes Advanced REST extension and with any request using this tool node crashes immediately.

I'm new to MEAN so am I missing something here that is causing the crash? Any ideas?

Mika Sundland
  • 18,120
  • 16
  • 38
  • 50
MTD
  • 609
  • 1
  • 5
  • 6
  • Try running your server manually and see if any errors get printed before it crashes: `node server.js` – robertklep May 27 '16 at 16:17
  • Running manually seems to solve the problem, thank. Does that mean I have some issue or misconfiguration with Grunt? – MTD May 27 '16 at 18:21
  • Not really. I assumed that by running it standalone, you would get to see _why_ it crashes. It wasn't supposed to work better that way ;D – robertklep May 27 '16 at 18:23
  • Added the full gruntfile.js, default.js, and dev.js that are being used and cause the error. Hoping that helps somehow. – MTD May 27 '16 at 19:02
  • Now testing with `node --debug server.js` I get the error message `Segmentation fault: 11` and node crashes. But if I don't use `--debug` there is no crash and no error message – MTD May 28 '16 at 15:26

33 Answers33

93

This is happening because of all the running server processes in the background. So all you need to do is stop them from the terminal.

Quick trick


FOR LINUX

Kill them all by running this on terminal:

pkill -f node

And then restart nodemon.


FOR Windows

 1. Go to the task manager
 2. Then look for Node.js: Server-side JavaScript
 3. Then right click on it and End task from the processes. 

Then restart the server. It will work fine.

Matin
  • 173
  • 2
  • 15
as8297
  • 1,089
  • 7
  • 6
16

for windows users, go to the task manager and then find for node.js server-side javascript, and end task on the process. then try again with your command.

Jasim Uddin
  • 179
  • 1
  • 11
  • 1
    I tried to kill the running server in the terminal with various commands...non worked but this simple trick did it. Thanks @Jamim Uddin. – Ashique Desai May 29 '20 at 13:15
11

In the terminal using the below command to kill the existing running port and restart your service.

killall -9 node

or to kill a particular port instead of all

sudo lsof -i :3000 //replace 3000 with your port number
sudo kill -9 31363 // replace 31363 with your PID
Siva
  • 375
  • 3
  • 5
  • 1
    That works, thanks! Unlike "pkill -f node" from the answer above – Liker777 Apr 18 '22 at 06:04
  • How do you find the PID? I'm also on Linux. – Shane G Apr 23 '22 at 11:22
  • @ShaneG sudo lsof -i :3000 (here 3000 is the port of your running application) this will return below type of response COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME php 1159083 SIVA 11u IPv4 8207821 0t0 TCP localhost:3000 (LISTEN) here you can see the PID at second column here my PID for port 3000 is 1159083 – Siva Apr 28 '22 at 16:38
7

Sometimes it happenes when you forget to source your .env files

7

Issue : app crashed - waiting for file changes before starting...

There could be different reasons:

1. Running node in background

pkill -f node

Worked in Mac OS ,did not work in Microsoft.

2.Server.js and package.json are not in same folder . Check it .

check package.json

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
     "start": "nodemon Server.js"
 }
3

I update node from v4.2.6 to v4.4.5 fixed the issue with the default mean.js install. I'll build out from there.

MTD
  • 609
  • 1
  • 5
  • 6
  • I suggest you to switch to last node LTS version : 8.9.3. Or at least the last LTS node 4.x : 4.8.7. Easy move with nvm (https://github.com/creationix/nvm). – MathKimRobin Dec 29 '17 at 15:50
2

Most likely your node daemon is still running.

ps -eaf | grep node

if it gives something like

abhinav 15759 15748 0 19:30 pts/2 00:00:00 sh -c nodemon server.js abhinav 15760 15759 0 19:30 pts/2 00:00:00 node /home/abhinav/Documents/Projects/WebD/Node/smartbrain/smart-brain-api/node_modules/.bin/nodemon server.js abhinav 15812 15801 0 19:31 pts/2 00:00:00 sh -c nodemon server.js

then try:

killall node

Abhinav Anand
  • 573
  • 3
  • 5
  • 19
2

I haven't used MongoDB for more than a month. So it automatically paused the MongoDB cluster in the MongoDB cloud (atlas). I resumed the cluster and restart the application (along with a recheck of the mongo connection URL which was saved in default.json).

This is how it worked for me.

Saravanan G
  • 581
  • 1
  • 9
  • 26
1

This can actually be because of an error that is breaking your project. Read throught the syntax error and get a better understanding on where the

0

In case your PORT is used by previous node process(tasks)

Run command netstat -a -n -o | find "8080" cmd1

And pass opened task using below command

taskkill /F /PID "1544"

cmd2

0

If anyone is still experiencing this problem, you may want to check if the syntax is correct and all node options you're using are still supported.

For instance, I've had the following mistake: MongoParseError: options poolsize, usenewurlparse are not supported so I removed these parameters and the server runned - here's the solution that worked for me

The "App crashed" error mainly occurs because of syntax errors, so if you're struggling even after you restarted everything, make sure to check the syntax of your code as well as the version you're using for Node.

0

It can also be because the MongoClient options you used are the deprecated ones.

For example, use maxPoolSize instead of poolSize, use wtimeoutMS instead of wtimeout.

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
0

Check the node version. Its always recommended to use a stable node version rather going for the latest version, which may create some issues while the program. I updated the npm to the specific version -v14.16.7 for my app, by using the nvm install / Note: You can use any version as your preference.

nvm is the node version manager. You can download it from : https://github.com/coreybutler/nvm-windows/release

nvm is mainly used for the version control of the node.

0

In my case, I had wrong database port configured

Change DB_PORT to 8889 in .env file fixed it.

So there is possibility of wrong app configuration, behind crashing of app.

0

This error might be comes when we pass other values then string in response.send() if you pass some numeric value in response.send(9) then it gives error so, you can pass response.send("9"), response.send only allow to send string values

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
0

Simply try changing the port number.

Mansi mishra
  • 442
  • 1
  • 5
  • 11
0
  • Stop the nodemon then
  • Start again

Note: Killing the node task in windows Task Manager worked fine than simply stopping and starting the nodemon.

Kamran Riyaz
  • 79
  • 2
  • 3
0

I actually came across the issue something similar to this. If you are using MongoDB then make sure that the cluster is connected to an IP address. This solved my issue. Try this if other solutions don't work for you. Have great day!

  • This does not really answer the question. If you have a different question, you can ask it by clicking [Ask Question](https://stackoverflow.com/questions/ask). To get notified when this question gets new answers, you can [follow this question](https://meta.stackexchange.com/q/345661). Once you have enough [reputation](https://stackoverflow.com/help/whats-reputation), you can also [add a bounty](https://stackoverflow.com/help/privileges/set-bounties) to draw more attention to this question. - [From Review](/review/late-answers/34427433) – treckstar May 26 '23 at 06:18
-1

I encountered this challenge when working on nexmo sms app.

To fix the crashing, go to your app.js. If you have these lines of code. Its normally on the very first lines...

`import { Socket } from 'dgram';`

`const express = require('express');`
`const bodyParser = require('body-parser');`
`const ejs = require('ejs');`
`const Nexmo = require('nexmo');`
`const socketio = require('socket.io');`

Simply delete/remove the first line of code import { Socket } from 'dgram';

Leaving these ones...

    `const express = require('express');`
    `const bodyParser = require('body-parser');`
    `const ejs = require('ejs');`
    `const Nexmo = require('nexmo');`
    `const socketio = require('socket.io');`

and restart your application using "nodemon"

Did it work?

umekalu
  • 169
  • 1
  • 5
-1

This can happen with incorrect paths.

Example: If your nodemon server.js path is in D:\Ex-Track\mern-exercise but If you are didn't use the full path D:\Ex-Track in your grunt, this can cause nodemon to fail.

LessQuesar
  • 3,123
  • 1
  • 21
  • 29
-1

This usually happens when you make changes to the server, while your server is running. For instead when you git pull to make changes to your server. Therefore, you need to kill the PID of the server that is running.

On windows you need to run the following commands:

> **netstat -ano|findstr "PID :3000"** // Replace 3000 with the port number
> **taskkill /pid 18264 /f** // Replace the 18264 with the pid number you received by running the first command

On Linux/Unix system you need to run the following commands:

> **lsof -i tcp:3000**
> **Kill -9 18264** 
-1

!!! that works for me

[nodemon] app crashed - waiting for file changes before starting... means you changes the file exactly at the time you save (nodemon debugger) working, try to use history to go back your changes. just that. if your changes can not be back from history do these steps:

Delete your nodemon in your ROOT node module like in this picture

MacBook-Pro:/usr/local/lib$ cd node_modules/
MacBook-Pro:/usr/local/lib/node_modules$ ls
expo-cli/         npm/              react-native-cli/
nodemon/          react-devtools/
MacBook-Pro:/usr/local/lib/node_modules$ sudo rm -R n
nodemon/ npm/     
MacBook-Pro:/usr/local/lib/node_modules$ sudo rm -R nodemon/
MacBook-Pro:/usr/local/lib/node_modules$ 

then install nodmon again !!

Farbod Aprin
  • 990
  • 1
  • 10
  • 20
-1

Try changing the default user password in mongoDB (Database Access->user). This solved the issue for me.

BDL
  • 21,052
  • 22
  • 49
  • 55
-1

I think this error can be caused for many reasons (it is not a very descriptive error to be honest), in my case it was because the "html-pdf" module had conflicts, I removed it and now the error is gone!.

R0bertinski
  • 517
  • 6
  • 12
-1
"scripts": {
   "start": "nodemon script.js"
}

Here, after nodemon write file name which you want to run like I have written script.js in package.json.

I hope it will help you.

Luis Paulo Pinto
  • 5,578
  • 4
  • 21
  • 35
SHACHI PRIYA
  • 105
  • 1
  • 2
-1

Easier way to kill node.js services on Windows is simply to run this command in command prompt

taskkill /im node.exe /F
Adam Wolf
  • 1
  • 2
-1

That is just because you have incorrect password in the configuration for mongoURI where your username is one but the password is incorrect. Just so find the right password for the created cluster , and then save that should work for MERN stack

-1

Just save "Express route" file to be able to restart, An error may have occurred during running (exception or anything other)

CBRS
  • 1
  • 2
-1

Might be very simple - if you see this issue in the console, scroll a bit up. If there's an issue in your code it will write the exact location.

Chen Mualem
  • 7
  • 1
  • 1
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/30313895) – Mario Petrovic Nov 11 '21 at 12:36
  • 1
    I got to this question by looking for the same error, but I understand it's not the same root cause as they had. I thought it was ok to add the action that helped me. I will be more specific next time. – Chen Mualem Nov 12 '21 at 19:01
-1

Simply try to move your app.js in outside the public folder.

ouflak
  • 2,458
  • 10
  • 44
  • 49
Rozza Haraa
  • 49
  • 1
  • 3
-2

Make sure your system time is not backward and higher. Reset your system time, so it could connect to the mongoose server if you are using online db.

isofttechn
  • 400
  • 1
  • 6
  • 19
-2

You can try the same way I solved it first. Go to the task manager Then look for Node.js: Server-side JavaScript Then right click on it and End task from the processes. Then restart the server. It will work fine.

  • 1
    This has already been mentioned in other answers. – Eric Aya May 01 '22 at 19:36
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Amit May 02 '22 at 12:05
-2

This is my error: [nodemon] app crashed - waiting for file changes before starting...

My answer: Make sure that we: 1- install bcrypt:

npm install bcrypt-nodejs

2- defined bcrypt:

const bcrypt = require('bcrypt-nodejs');
Jakub Kurdziel
  • 3,216
  • 2
  • 12
  • 22