gulpfile browsersync nodemon太多ram

时间:2015-01-29 00:28:25

标签: javascript express gulp nodemon browser-sync

我的gulpfile无法正常运行。当我运行默认任务gulp时,我的浏览器已启动但挂在左下角的waiting for localhost...处。如果我刷新,那么服务器按预期工作。我还想编辑我的代码并在浏览器中显示更新。这个功能有效,但在开发一段时间后,吞咽量增加到约300mb。

'use strict';
process.env.DEBUG = process.env.DEBUG || 'r3dm:*';
var gulp = require('gulp'),

    // ## Style
    concat = require('gulp-concat'),
    stylus = require('gulp-stylus'),
    swiss = require('kouto-swiss'),
    mincss = require('gulp-minify-css'),

    // ## Bundle
    browserify = require('browserify'),
    watchify = require('watchify'),
    envify = require('envify/custom')({ NODE_ENV: 'development' }),
    uglifyify = require('uglifyify'),
    bundleName = require('vinyl-source-stream'),
    //brfs = require('brfs'),

    // ## utils
    plumber = require('gulp-plumber'),
    util = require('gulp-util'),
    noopPipe = util.noop,
    //logPipe = util.log,
    watch = require('gulp-watch'),
    yargs = require('yargs').argv,
    debug = require('debug')('r3dm:gulp'),

    // ## min
    imagemin = require('gulp-imagemin'),
    //pngcrush = require('imagemin-pngcrush'),

    // ## Serve/Proxy/Reload
    nodemon = require('gulp-nodemon'),
    sync = require('browser-sync'),
    reload = sync.reload,

    // ## React
    react = require('gulp-react'),

    // ## production?
    production = yargs.p;

var paths = {
  main: './client.js',
  jsx: './components/**/**.jsx',
  stylusMain: './components/app.styl',
  stylusAll: './components/**/*.styl',
  css: './public/css/',
  server: './server.js',
  serverIgnore: [
    'gulpfile.js',
    'public/',
    'components/**/*.styl',
    'bower_components/',
    'node_modules/'
  ],
  publicJs: './public/js'
};

var watching = false;
var reloadDelay = 6500;

if (production) {
  // ## Set with `-p`
  console.log('\n', 'Production mode set', '\n');
}

gulp.task('stylus', function() {
  return gulp.src(paths.stylusMain)
    .pipe(plumber())
    .pipe(stylus({
      use: [
        swiss()
      ],
      'include css': true
    }))
    .pipe(concat('main.css'))
    .pipe(production ? mincss() : noopPipe())
    .pipe(gulp.dest(paths.css));
});

gulp.task('jsx', function() {
  return gulp.src('./components/**/*.jsx')
    .pipe(react())
    .pipe(gulp.dest('./components'));
});

gulp.task('jsx-watch', function() {
  return gulp.src(paths.jsx)
    .pipe(watch(paths.jsx))
    .pipe(react({
      harmony: true
    }))
    .pipe(gulp.dest('./components'));
});

gulp.task('bundle', function(cb) {
  browserifyCommon(cb);
});

gulp.task('sync', ['bundle', 'stylus', 'server'], function() {
  sync.init(null, {
    proxy: 'http://localhost:9000',
    logLeval: 'debug',
    files: [
      'public/**/*.*',
      '!public/js/bundle.js'
    ],
    port: 9002,
    open: true,
    reloadDelay: reloadDelay
  });
});

gulp.task('server', function(cb) {
  var called = false;
  nodemon({
    script: paths.server,
    ext: '.js',
    ignore: paths.serverIgnore,
    env: {
      'NODE_ENV': 'development',
      'DEBUG': 'r3dm:*'
    }
  })
    .on('start', function() {
      if (!called) {
        called = true;
        setTimeout(function() {
          cb();
        }, reloadDelay);
      }
    })
    .on('restart', function(files) {
      if (files) {
        debug('Files that changed: ', files);
      }
      setTimeout(function() {
        debug('Restarting browsers');
        reload();
      }, reloadDelay);
    });
});

gulp.task('watch', function() {
  gulp.watch(paths.stylusAll, ['stylus']);
});

gulp.task('setWatch', function() {
  watching = true;
});

gulp.task('image', function() {
  gulp.src('images/**/*')
    .pipe(imagemin({
      progressive: true,
      optimizationLevel: 2
    }))
    .pipe(gulp.dest('public/images'));
});

gulp.task('default', [
  'setWatch',
  'jsx-watch',
  'bundle',
  'stylus',
  'server',
  'sync',
  'watch'
]);

function browserifyCommon(cb) {
  cb = cb || noop;
  var config;

  if (watching) {
    config = {
      basedir: __dirname,
      debug: true,
      cache: {},
      packageCache: {}
    };
  } else {
    config = {
      basedir: __dirname
    };
  }

  var b = browserify(config);
  b.transform(envify);
  //b.transform(brfs);

  if (!production) {
    debug('Watching');
    b = watchify(b);
    b.on('update', function() {
      bundleItUp(b);
    });
  }

  if (production) {
    debug('Uglifying bundle');
    b.transform({ global: true }, uglifyify);
  }

  b.add(paths.main);
  bundleItUp(b);
  cb();
}

function bundleItUp(b) {
  debug('Bundling');
  return b.bundle()
    .pipe(plumber())
    .pipe(bundleName('bundle.js'))
    .pipe(gulp.dest(paths.publicJs));
}

function noop() { }

update :它可能不是我的gulpfile。我耐心地等待它最终加载我的应用程序的根页面。这是我的server.js文件

'use strict';
require('dotenv').load();
require('newrelic');
var express = require('express'),
    app = express(),
    keystone = require('keystone'),
    mongoose = require('mongoose'),

    // ## Util
    debug = require('debug')('r3dm:server'),
    utils = require('./utils/utils'),

    // ## React
    React = require('react'),
    Router = require('./components/Router'),
    state = require('express-state'),

    // ## Flux
    Fetcher = require('fetchr'),
    mandrillServ = require('./services/mandrill'),
    blogServ = require('./services/blog'),
    ContextStore = require('./components/common/Context.store'),
    RouterStateAction = require('./components/common/RouterState.action'),

    // ## Express/Serve
    morgan = require('morgan'),
    serve = require('serve-static'),
    favicon = require('serve-favicon'),
    body = require('body-parser'),
    multer = require('multer'),
    compress = require('compression'),
    cookieParser = require('cookie-parser'),
    session = require('express-session'),
    flash = require('connect-flash'),
    helmet = require('helmet');

// ## State becomes a variable available to all rendered views
state.extend(app);
app.set('state namespace', 'R3DM');

app.set('port', process.env.PORT || 9000);
app.set('view engine', 'jade');
app.use(helmet());
app.use(morgan('dev'));
app.use(favicon(__dirname + '/public/images/favicon.ico'));
app.use(cookieParser('12345'));
app.use(body.urlencoded({ extended: false }));
app.use(body.json());
app.use(multer());
app.use(compress());
app.use(flash());
app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true
}));

// ## Fetcher middleware
Fetcher.registerFetcher(mandrillServ);
Fetcher.registerFetcher(blogServ);
app.use('/api', Fetcher.middleware());

keystone.app = app;
keystone.mongoose = mongoose;
keystone.init({
  'cookie secret': '12345',
  'auth': true,
  'user model': 'User',
  'mongo': process.env.MONGO_URI,
  'session': true
});

keystone.import('models');
keystone.static(app);
keystone.routes(app);
keystone.mongoose.connect(keystone.get('mongo'));

app.use(serve('./public'));

app.get('/500', function(req, res) {
  res.render('500');
});

app.get('/emails/:name', function(req, res) {
  var locals = {},
      name = req.params.name,
      nameArr;

  nameArr = name
    .split(' ')
    .map(function(_name) {
      _name = _name.replace(/[^A-Za-z_'-]/gi, '');
      _name = utils.capitalize(_name);
      return _name;
    });

  locals.name = nameArr[0];
  res.render('email/greet', locals);
});

app.get('/*', function(req, res, next) {
  debug('req', req.path);
  debug('decode req', decodeURI(req.path));
  Router(decodeURI(req.path))
    .run(function(Handler, state) {
      Handler = React.createFactory(Handler);
      debug('Route found, %s ', state.path);

      var ctx = {
        req: req,
        res: res,
        next: next,
        Handler: Handler,
        state: state
      };

      debug('Sending route action');
      RouterStateAction(ctx);
    });
});

// Use a hot observable stream for requests
var hotObservable = ContextStore.publish();

// Run on next sequence
hotObservable.subscribe(function(ctx) {
  if (!ctx.Handler) { return debug('no handler'); }
  debug('rendering react to string', ctx.state.path);
  var html = React.renderToString(ctx.Handler());
  debug('rendering jade');

  ctx.res.render('layout', { html: html }, function(err, markup) {
    if (err) { return ctx.next(err); }

    debug('Sending %s', ctx.state.path);
    return ctx.res.send(markup);
  });
});

// Start listening listening to observable sequence;
hotObservable.connect();

app.use(function(req, res) {
  res.status(404);
  res.render(404);
});

app.use(function(err, req, res, next) { //jshint ignore:line
  debug('Err: ', err);
  res
    .status(500)
    .send('Something went wrong');
});

// keystone.start();
app.listen(app.get('port'), function() {
  debug('The R3DM is go at: ' + app.get('port'));
  debug(new Date());
});

debug('req', req.path);最终在~120秒后达到。但是如果我在第一次打开标签时刷新它会立即加载。

update 2 :我能够通过将dealy增加到6500ms来修复初始加载问题。现在我需要找到导致内存泄漏的原因。

0 个答案:

没有答案