Grunt开发EADDRINUSE

时间:2014-08-22 19:49:12

标签: node.js express gruntjs

这是我的Gruntfile:

module.exports = function(grunt) {

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    watch: {
      serve: {
        files: ['server.js', 'src/**/*.coffee'],
        tasks: ['coffee', 'develop'],
        options: {
          nospawn: true
        }
      },
      css: {
        files: ['lib/less/main.less'],
        tasks: ['less'],
        options: {
          nospawn: true
        }
      },
      test: {
        ...
      }
    },

    jasmine_node: {
     ...
    },
    develop: {
      server: {
        file: 'server.js'
      }
    },
    coffee: {
      compile: {
        expand: true,
        bare: true,
        cwd: 'src/',
        src: ['**/*.coffee'],
        dest: 'lib/',
        ext: '.js'
      }
    },
    copy: {
    ...
    },

    jasmine: {
      ...
    },
    less: {
      ..
    },
    concurrent: {
      options: {
        logConcurrentOutput: true
      },
      serve: {
        tasks: ["watch:css", "watch:serve"]
      },
    }
  });

  grunt.loadNpmTasks('grunt-contrib-coffee');
  ...
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-concurrent');
  grunt.registerTask('serve', ['coffee', 'develop', 'concurrent:serve']);
  grunt.registerTask('test', ['coffee', 'jasmine_node'/*, 'watch:test'*/]);
  grunt.registerTask('build', ['coffee', 'less']);
  grunt.registerTask('templates', ['copy']);

};

问题:第一次启动服务器时,编辑咖啡文件后我的服务器抛出错误EADDRINUSE,但仍然可以访问网址(因此第一台服务器没有关机)。完整项目:http://github.com/OpenCubes/OpenCubes

[grunt-develop] >
events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: listen EADDRINUSE
  at errnoException (net.js:904:11)
  at Server._listen2 (net.js:1042:14)
  at listen (net.js:1064:10)
  at net.js:1146:9
  at dns.js:72:18
  at process._tickCallback (node.js:419:13)

>> application exited with code 8

1 个答案:

答案 0 :(得分:1)

您指定的行为符合预期。当您启动监视任务时,它会在指定端口上激活您的服务器。但是,保存时,监视任务会尝试在同一端口上再次启动服务器,但服务器实例已在该端口上运行。因此,您会收到EADDRINUSE错误,因为该端口已在使用中。

当您杀死grunt任务时,它会终止进程,其中包括您正在运行的服务器。

要解决您的问题(虽然问题有点不清楚),您需要在同一端口上启动新服务器之前终止服务器。最简单的方法可能是包含grunt-nodemon之类的模块或专门用于express的众多模块之一。

此外,如果您需要运行服务器进行测试,那么如果您使用supertest进行操作,则不需要让服务器收听端口测试你的API。