Arkadiy Stepanov
Arkadiy Stepanov

Reputation: 181

Starting an express server from within gulp

I have a server.js file in the same directory with gulpfile.js. In gulpfile.js I require my server.js file:

var express = require('./server.js')

I want to run it in the default task:

gulp.task('default' , [ 'build','watch','connect'] , function(){
    gulp.run('express');
});

I tried to run it like that but it didn't work. I suppose you can run only tasks in that way. How can I run it in default task?

The server.js file includes this code:

var express = require('express');
var app = express(); 

app.get('/api/test', function(req,res){
  res.send('Hello world!')
});

app.listen(3000, function(){
  console.log('Example app listening on port 3000!');
})

Upvotes: 5

Views: 7398

Answers (3)

Silviu Burcea
Silviu Burcea

Reputation: 5348

Quite late at the party, but you might want to use nodemon:

const nodemon = require('gulp-nodemon');
// ...
gulp.task('server', () => {
  nodemon({
    script: 'server.js'
  });
});

Upvotes: 2

Arkadiy Stepanov
Arkadiy Stepanov

Reputation: 181

The solution to that would be just replacing my code with the following :

gulp.task('default' , [ 'build','watch','connect'] , function(){
  express;
});

Upvotes: 1

Sven Schoenung
Sven Schoenung

Reputation: 30564

The gulp-live-server package allows you (among other things) to start an express server from your own server script:

var gulp = require('gulp');
var gls = require('gulp-live-server');

gulp.task('default', [ 'build','watch','connect'], function() {
  var server = gls.new('./server.js');
  return server.start();
});

Using the code above you can start your server by running gulp on the command line. The server will run until you hit Ctrl+C in the terminal.

Upvotes: 4

Related Questions