Не могу остановить работу сервера на nodemon

Я создаю глоток для модульных тестов. Я добавляю nodemon для автоматического запуска сервера, а затем запускаю тест. Но есть ошибка при повторном запуске gulp task. У меня ошибка, что порт уже занят другим процессом.

Я пользуюсь этим кодом:

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() В сценарии сервера я добавляю обработчик события выхода из события, который останавливает сервер и успешно завершает задачу с остановленным сервером.

1 ответ

Решение

Нодемон имеет quit команда. Ознакомьтесь с разделом Использование событий nodemon, а также с вашим модулем и его документами. Согласно документации вы можете использовать:

var nodemon = require('nodemon');

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

Другие вопросы по тегам