node.js nodemon 应用程序崩溃 - 在启动之前等待文件更改

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37486631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:15:59  来源:igfitidea点击:

nodemon app crashed - waiting for file changes before starting

angularjsnode.jsmean-stackgrunt-nodemon

提问by MTD

EDITAfter 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.

编辑经过进一步测试,我发现这个应用程序和 mean.js 的默认安装上的 gulp 和 grunt 都会发生这种情况。我在 Mac 上本地运行它。当我使用“node server.js”运行任一应用程序时,它们都不会崩溃。

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.

我正在使用带有 grunt-nodemon 的 MEAN 堆栈,并且在访问快速 URL 时节点崩溃。但它并不总是一致的。有时它可以工作,有时当 URL 被点击时节点崩溃,没有数据退出,有时我收到响应并且节点立即崩溃。

Browser console response:

浏览器控制台响应:

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

Terminal output:

终端输出:

Mongoose: users.insert({ firstname: 'mike', lastname: 'jones', email:'[email protected]', 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.

在这种情况下,POST 请求通过,用户被添加,然后节点崩溃,但有时它在成功 POST 之前崩溃。Node 偶尔也会在 GET 请求上崩溃。

gruntfile.js:

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

默认.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:

开发.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.

我也在使用 Chromes Advanced REST 扩展进行测试,并且使用此工具节点的任何请求都会立即崩溃。

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

我是 MEAN 的新手,所以我在这里错过了导致崩溃的东西吗?有任何想法吗?

回答by as8297

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

这是因为所有在后台运行的服务器进程。所以你需要做的就是从终端阻止它们。

Quick trick

快招

Kill them all by running this on terminal :

通过在终端上运行这个来杀死他们:

pkill -f node

and then restart nodemon.

然后重启nodemon。

Let me know if it helps and upvote it please.Thank you.

让我知道它是否有帮助并请点赞。谢谢。

回答by Jasim Uddin

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

对于 Windows 用户,转到任务管理器,然后找到 node.js 服务器端 javascript,并在该过程中结束任务。然后用你的命令再试一次。

回答by MTD

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.

我将节点从 v4.2.6 更新到 v4.4.5 修复了默认 mean.js 安装的问题。我会从那里建立起来。

回答by umekalu

I encountered this challenge when working on nexmo sms app.

我在开发 nexmo 短信应用时遇到了这个挑战。

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

要修复崩溃,请转到您的app.js. 如果你有这些代码行。它通常在第一行......

`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';

只需删除/删除第一行代码 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"

并使用“nodemon”重新启动您的应用程序

Did it work?

它起作用了吗?

回答by Abhinav Anand

Most likely your node daemon is still running.

很可能您的节点守护程序仍在运行。

ps -eaf | grep node

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

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

killall node

回答by Siva

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

在终端中使用以下命令杀死现有正在运行的端口并重新启动您的服务。

killall -9 node

回答by isoftTech

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.

确保您的系统时间不落后和更高。重置您的系统时间,如果您使用在线数据库,它可以连接到猫鼬服务器。

回答by user13490860

This can happen with incorrect paths.

不正确的路径可能会发生这种情况。

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

示例:如果您的nodemon server.js路径在D:\Ex-Track\mern-exercise但如果您没有D:\Ex-Track在 grunt 中使用完整路径,这可能会导致 nodemon 失败。