Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!');
})
like image 475
Arkadiy Stepanov Avatar asked Dec 24 '16 16:12

Arkadiy Stepanov


People also ask

How do I use gulp locally?

To install Gulp locally, navigate to your project directory and run npm install gulp . You can save it to your package. json dependencies by running npm install gulp --save-dev . Once you have Gulp installed locally, you can then proceed to create your gulpfile.

Can we create server using Express?

Express allows us to get to "Hello World" with a server quickly. We'll create a basic server with a single route, create a middleware to log requests that we receive, as well as start our server listening on for requests on our localhost.


3 Answers

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

const nodemon = require('gulp-nodemon');
// ...
gulp.task('server', () => {
  nodemon({
    script: 'server.js'
  });
});
like image 33
Silviu Burcea Avatar answered Oct 02 '22 17:10

Silviu Burcea


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.

like image 143
Sven Schoenung Avatar answered Oct 02 '22 17:10

Sven Schoenung


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

gulp.task('default' , [ 'build','watch','connect'] , function(){
  express;
});
like image 26
Arkadiy Stepanov Avatar answered Oct 02 '22 17:10

Arkadiy Stepanov