nodemon 无法停止服务器 运行

Can't stop server running by nodemon

我为单元测试创​​建了 gulp 任务。我为自动 运行 服务器添加 nodemon 然后 运行 测试。但是当运行 gulp 任务再次出现错误。我有错误,端口已经忙于另一个进程。

我使用此代码:

var gulp = require('gulp'),
    gulpUtil = require('gulp-util'),
    gulpShell = require('gulp-shell'),
    gulpEnv = require('gulp-env'),
    gulpNodemon = require('gulp-nodemon'),
    gulpMocha = require('gulp-mocha');

gulp.task('default', function () {
    gulpUtil.log('unit - run unit tests');
});

gulp.task('server', function (callback) {
    var started = false;

    return gulpNodemon({
        script: './build/app.js'
    })
        .on('start', function () {
            if (!started) {
                started = true;

                return callback();
            }
        })
});

gulp.task('unit', ['server'], function () {
    return gulp.src('./src/*.js')
        .pipe(gulpMocha({reporter: 'spec'}))
        .once('error', function () {
            process.exit(1);
        })
        .once('end', function () {
            process.exit();
        })
});

如何在单元测试后停止或终止服务器?

补充回答: 现在我有 gulpfile.js:

var gulp = require('gulp'),
    gulpUtil = require('gulp-util'),
    gulpNodemon = require('gulp-nodemon'),
    gulpMocha = require('gulp-mocha'),
    gulpShell = require('gulp-shell');
var runSequence = require('run-sequence');
var nodemon;

gulp.task('default', function () {
    gulpUtil.log('compile - compile server project');
    gulpUtil.log('unit - run unit tests');
});

gulp.task('compile', function () {
    return gulp.src('./app/main.ts')
        .pipe(gulpShell([
            'webpack'
        ]))
});

gulp.task('server', function (callback) {
    nodemon = gulpNodemon({
        script: './build/app.js'
    })
        .on('start', function () {
            return callback();
        })
        .on('quit', function () {
        })
        .on('exit', function () {
            process.exit();
        });

    return nodemon;
});

gulp.task('test', function () {
    return gulp.src('./src/*.js')
        .pipe(gulpMocha({reporter: 'spec'}))
        .once('error', function () {
            nodemon.emit('quit');
        })
        .once('end', function () {
            nodemon.emit('quit');
        });
});


gulp.task('unit', function() {
    runSequence('compile', 'server', 'test');
});

还在我的服务器脚本中添加了这个片段:

this.appListener = this.http.listen(process.env.PORT || 3000, '0.0.0.0', function() {
  console.log(chalk.green("Server started with port " + _this.appListener.address().port));
});
// **Add**
function stopServer() {
  console.log(chalk.cyan('Stop server'));
  process.exit();
}
process.on('exit', stopServer.bind(this));
process.on('SIGINT', stopServer.bind(this));

因此,当测试完成并且我在服务器脚本中调用 process.exit() 我添加事件 exit 停止服务器的事件处理程序和 gulp 任务成功完成服务器已停止。

Nodemon 有一个 quit 命令。看看 Using nodemon events and concerning your module also its docs。根据您可以使用的文档:

var nodemon = require('nodemon');

// force a quit
nodemon.emit('quit');