Skip to content

Instantly share code, notes, and snippets.

@sogko
Last active Jun 21, 2022
Embed
What would you like to do?
gulp + expressjs + nodemon + browser-sync
'use strict';
// simple express server
var express = require('express');
var app = express();
var router = express.Router();
app.use(express.static('public'));
app.get('/', function(req, res) {
res.sendfile('./public/index.html');
});
app.listen(5000);
'use strict';
var gulp = require('gulp');
var browserSync = require('browser-sync');
var nodemon = require('gulp-nodemon');
gulp.task('default', ['browser-sync'], function () {
});
gulp.task('browser-sync', ['nodemon'], function() {
browserSync.init(null, {
proxy: "http://localhost:5000",
files: ["public/**/*.*"],
browser: "google chrome",
port: 7000,
});
});
gulp.task('nodemon', function (cb) {
var started = false;
return nodemon({
script: 'app.js'
}).on('start', function () {
// to avoid nodemon being started multiple times
// thanks @matthisk
if (!started) {
cb();
started = true;
}
});
});
<html>
<head>
<link rel="stylesheet" href="site.css"/>
</head>
<body>
<!-- some dummy non-conforming quick dirty html code to test browser-sync. dont't judge me. -->
<b>lorem</b> ipsum upsum dumsum
</body>
</html>
<!-- put this under /public/* -->
{
"name": "gulp-expressjs-nodemon-browser-sync",
"version": "0.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": {
"name": "Hafiz Ismail",
"email": "hafiz@wehavefaces.net",
"url": "http://wehavefaces.net"
},
"license": "ISC",
"dependencies": {
"express": "^4.8.2"
},
"devDependencies": {
"browser-sync": "^1.3.3",
"gulp": "^3.8.7",
"gulp-nodemon": "^1.0.4"
}
}
/* some css */
/* put this under /public/* */
body {
font-family: 'Helvetica';
color: red;
font-size:24px;
}
@js-writer
Copy link

js-writer commented Jan 26, 2016

Thx. I was looking for something like this!

@MacgyverMartins
Copy link

MacgyverMartins commented Feb 27, 2016

Thanks man. This help me a lot!

@rakeshongithub
Copy link

rakeshongithub commented Mar 25, 2016

very helpfull

@emveeoh
Copy link

emveeoh commented Apr 3, 2016

Thank you!

@tomekrozalski
Copy link

tomekrozalski commented Apr 19, 2016

Holy moly, works fantastic! 👯

@ohsiwon
Copy link

ohsiwon commented May 13, 2016

This is great! Thank you!

@jcloutz
Copy link

jcloutz commented May 25, 2016

This i awesome, thank you for posting!

@gcfabri
Copy link

gcfabri commented Jun 23, 2016

Thank you, very helpful!

@buffaloo
Copy link

buffaloo commented Jul 13, 2016

great gulp-recipe.

@AlbertoFdzM
Copy link

AlbertoFdzM commented Jul 27, 2016

Just as info if you change the package nodemon for gulp-nodemon you'll get the nodemon log traces too in the console. worth it.

@akhileshmohan
Copy link

akhileshmohan commented Aug 3, 2016

Very useful conversation..thank you all

@github-polymer-user
Copy link

github-polymer-user commented Aug 11, 2016

man it works, now I'm able to simulate production server with express (and kills every ugly fat bug in a wheels)

@eldyvoon
Copy link

eldyvoon commented Aug 29, 2016

I got a forever loading, any clue why?

@deepank411
Copy link

deepank411 commented Sep 10, 2016

Hi

This link has a part of my projects gulpfile: http://hastebin.com/iwocigizaq.coffee
I tried your code snippet to integrate browsersync with nodemon but all it leads to is an infinite load. No code(html/js/css) is loaded.
I have tried putting the port and the browser but to a no different result. I also unsuccessfully tried the code from https://github.com/sogko/gulp-recipes/blob/master/browser-sync-nodemon-expressjs/gulpfile.js .
Also my terminal log shows the nodemon is running with no error.

Can you please have a look at the gulp task and let me know if I'm doing something incorrectly.

Thanks

@zootella
Copy link

zootella commented Oct 5, 2016

this is awesome. thanks.

@garrettmac
Copy link

garrettmac commented Nov 7, 2016

This is great. I used it to make a my grabs a projects 'dist' folder and move it into the 'public' folder https://gist.github.com/garrettmac/07b475ad1043ad9c79a49ee61963e497

@IanGrainger
Copy link

IanGrainger commented Nov 11, 2016

Great! I noticed my pages got out of date when I changed something that caused nodemon to restart, so I added:
nodemon.on...
.on('restart', function() {
browserSync.reload();
});

... Except it doesn't work because it calls the reload before the server has finished running up. Darn.

@sainthkh
Copy link

sainthkh commented Dec 9, 2016

According to API, var browserSync = require('browser-sync'); is changed to var browserSync = require('browser-sync').create(); in 2.0.

@sainthkh
Copy link

sainthkh commented Dec 9, 2016

For those who cannot run google chrome in windows:

Internally, browser-sync uses opn library. So, the name of browser is different from OS to OS. As for windows, it's not google chrome, it's just chrome. Other browsers:

  • Internet Explorer: iexplore
  • Firefox: firefox
  • Microsoft Edge: path.join(__dirname, ".bin", "edge.exe")

As Microsoft Edge doesn't have the way to call it by cmd start "some command for edge", so we need special command line program. I've downloaded it to projectRoot/.bin and changed its name to "edge.exe". So, the name of edge is really odd. However, when every setup is done, everything works nicely.

@coverboy
Copy link

coverboy commented Mar 4, 2017

Pretty Awesome!! Thanks.

@omadoyeabraham
Copy link

omadoyeabraham commented Mar 31, 2017

For those who have the "loading forever" issue, I had to install nodemon, and then run nodemon in a separate terminal for the gulp task to load. Don't know exactly why though.

@ChingizMizambekov
Copy link

ChingizMizambekov commented Apr 15, 2017

Nice job, thx!

@dkutelov
Copy link

dkutelov commented May 24, 2017

Works great! Thx!

@cooljl31
Copy link

cooljl31 commented Jun 13, 2017

Works great! Thx!

@sofakeer
Copy link

sofakeer commented Jun 20, 2017

Works great! Thx!

@david1542
Copy link

david1542 commented Nov 24, 2017

Does someone knows how to change the default behaviour of browser-sync which automatically delivers index.html as the root directory?
I tried changing that behaviour by simply defining a route inside my app.js but somehow it gets ignored.

@binler
Copy link

binler commented Mar 7, 2018

Nice job, but i have a question?
It's just working when i access http://localhost:3000, when I access http://localhost:3000/users it not working, help me?

@danielchikaka
Copy link

danielchikaka commented Aug 28, 2018

Looks promising but it breaks after running for the first time with this error:

`
Error: listen EADDRINUSE :::5000

at Object._errnoException (util.js:1022:11)

at _exceptionWithHostPort (util.js:1044:20)

at Server.setupListenHandle [as _listen2] (net.js:1351:14)

at listenInCluster (net.js:1392:12)

at Server.listen (net.js:1476:7)

at Function.listen (C:\xampp\htdocs\ndondo\aug2018\jobBoard\node_modules\express\lib\application.js:618:24)

at Object.<anonymous> (C:\xampp\htdocs\ndondo\aug2018\jobBoard\index.js:36:5)

at Module._compile (module.js:643:30)

at Object.Module._extensions..js (module.js:654:10)

at Module.load (module.js:556:32)

[18:01:36] [nodemon] app crashed - waiting for file changes before starting
`

Any ideas why ?

@Dmitri801
Copy link

Dmitri801 commented Dec 27, 2018

Heres a 2019 way of setting up the gulpfile since that code no longer works for running multiple tasks

const gulp = require("gulp");
const browserSync = require("browser-sync");
var nodemon = require("gulp-nodemon");

gulp.task("nodemon", cb => {
  let started = false;

  return nodemon({
    script: "server.js"
  }).on("start", () => {
    if (!started) {
      cb();
      started = true;
    }
  });
});

gulp.task(
  "browser-sync",
  gulp.series("nodemon", () => {
    browserSync.init(null, {
      proxy: "http://localhost:7000",
      files: ["public/**/*.*"],

      port: 9000
    });
  })
);

gulp.task("serve", gulp.series("browser-sync", () => {}));

@danydodson
Copy link

danydodson commented Feb 16, 2019

Thanks @Dmitri801, works great!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment