Gulp BrowserSync and npm start - gulp

I'd like to start my NodeJS application using BrowserSync but it seems not working.
Error message : Error: listen EADDRINUSE
Edit #1:
I found this way to resolve my issue.
gulp.task('sync', ['start', 'watch'], function(cb) {
browserSync.init({
files: ['**/*'],
proxy: 'http://localhost:3000',
port: 4000
});
});
gulp.task('start', function() {
var called = false;
return nodemon({
script: './bin/www',
watch: ['Application.js']
}).on('start', function onStart() {
if (!called) {
cb();
}
called = true;
}).on('restart', function onRestart() {
setTimeout(function reload() {
browserSync.reload({
stream: false
});
}, 500);
});
});

EADDRINUSE means that the port number which listen() tries to bind the server to is already in use. So, in your case, there must be running a server on port 80 already. If you have another webserver running on this port you will get the EADDRINUSE error.
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: ["**/*.*"],
browser: "google chrome",
port: 7000,
});
});
gulp.task('nodemon', function (cb) {
nodemon({
script: './bin/www/app.js'
})
.on('start', function () {
cb();
})
.on('error', function(err) {
// Make sure failure causes gulp to exit
throw err;
});
});
Hope it helps :)

Related

error: gulp.start is not a function while using gulp version 4

Iam using gulp CLI version: 2.2.1 Local version: 4.0.2
The node version is 12.16.3
MY code of gulpfile.js is
'use strict';
var gulp = require('gulp'),
sass = require('gulp-sass'),
browserSync = require('browser-sync'),
del=require('del'),
imagemin = require('gulp-imagemin'),
uglify = require('gulp-uglify'),
usemin = require('gulp-usemin'),
rev = require('gulp-rev'),
cleanCss = require('gulp-clean-css'),
flatmap = require('gulp-flatmap'),
htmlmin = require('gulp-htmlmin');
gulp.task('sass', function () {
return gulp.src('./css/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./css'));
});
gulp.task('sass:watch', function () {
gulp.watch('./css/*.scss', ['sass']);
});
gulp.task('browser-sync', function () {
var files = [
'./*.html',
'./css/*.css',
'./img/*.{png,jpg,gif}',
'./js/*.js'
];
browserSync.init(files, {
server: {
baseDir: "./"
}
});
});
// Default task
gulp.task('default', gulp.series('browser-sync', function() {
gulp.start('sass:watch');
}));
gulp.task('clean', function() {
return del(['dist']);
});
gulp.task('copyfonts', function() {
gulp.src('./node_modules/font-awesome/fonts/**/*.{ttf,woff,eof,svg}*')
.pipe(gulp.dest('./dist/fonts'));
});
gulp.task('imagemin', function() {
return gulp.src('img/*.{png,jpg,gif}')
.pipe(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true }))
.pipe(gulp.dest('dist/img'));
});
gulp.task('usemin', function() {
return gulp.src('./*.html')
.pipe(flatmap(function(stream, file){
return stream
.pipe(usemin({
css: [ rev() ],
html: [ function() { return htmlmin({ collapseWhitespace: true })} ],
js: [ uglify(), rev() ],
inlinejs: [ uglify() ],
inlinecss: [ cleanCss(), 'concat' ]
}))
}))
.pipe(gulp.dest('dist/'));
});
gulp.task('build',gulp.series('clean', function() {
gulp.start('copyfonts','imagemin','usemin');
}));
The error I got is after running gulp build on the command line is:
[15:38:33] Starting 'build'...
[15:38:33] Starting 'clean'...
[15:38:33] Finished 'clean' after 69 ms
[15:38:33] Starting '<anonymous>'...
[15:38:33] '<anonymous>' errored after 3.57 ms
[15:38:33] TypeError: gulp.start is not a function
at C:\Users\HARIKA\Desktop\bootstrapassign1\Bootstrap4\conFusion\gulpfile.js
:74:10
[15:38:33] 'build' errored after 83 m
I dont know how to solve the erros. I even changed some of tasks to gulp.series() as per version of gulp version 4. Can anyone help me to resolve the error? Thank you in advance.
Replace these two tasks:
// Default task
gulp.task('default', gulp.series('browser-sync', function() {
gulp.start('sass:watch');
}));
gulp.task('build',gulp.series('clean', function() {
gulp.start('copyfonts','imagemin','usemin');
}));
with:
// Default task
gulp.task('default', gulp.series('browser-sync', 'sass:watch'));
gulp.task('build',gulp.series('clean', 'copyfonts','imagemin','usemin'));
gulp.start is not a part of gulp4+ - it was in v3 although not really sanctioned for use even there.
I had the same issue and perhaps found the solution:
Replace the following:
gulp.task('sass:watch', function () {
gulp.watch('./css/*.scss', ['sass']);
// Default task
gulp.task('default', gulp.series('browser-sync', function() {
gulp.start('sass:watch');
}));
And add instead:
gulp.task('sass:watch', function() {
gulp.watch('./css/*.scss', gulp.series(['sass']));
// Default task
gulp.task('default', gulp.parallel('browser-sync', 'sass:watch'));
From what I have found you will have to use gulp.series and gulp.parallel interchangeably with gulp +4.x
Now for the second part change:
gulp.task('copyfonts', function() {
gulp.src('./node_modules/font-awesome/fonts/**/*.{ttf,woff,eof,svg}*')
.pipe(gulp.dest('./dist/fonts'));
});
Adding return here:
gulp.task('copyfonts', function() {
return gulp.src('./node_modules/font-awesome/fonts/**/*.{ttf,woff,eof,svg}*')
.pipe(gulp.dest('./dist/fonts'));
});
And like shown in the previous answer make the last task:
gulp.task('build', gulp.series('clean','copyfonts','imagemin','usemin'));
Hope this helps!

Gulp task not finishing

Being new to gulp. I have the follwing task. I need to spawn a webserver and then another script has to run some stuff against this webserver. I am currently struggling with finishing the script because the browser-sync task does not finish and prevents the script from exit.
'use strict';
const browserSync = require('browser-sync').create();
const cp = require('child_process');
const minimalcss = require('minimalcss');
const gulp = require('gulp');
const clean = require('gulp-clean');
const sourceDir = "_site/";
const deployDir = "public/";
// build the mkdocs Site
gulp.task('build', function() {
return cp.exec('pipenv run mkdocs build --site-dir ' + sourceDir);
});
// Delete _deploy directory first
gulp.task('prepare', function() {
return gulp.src(deployDir, {read: false, allowEmpty: true})
.pipe(clean());
});
// Delete _deploy directory again // just for testing
gulp.task('cleanup', function() {
return gulp.src(deployDir, {read: false, allowEmpty: true})
.pipe(clean());
});
// does not lead to anything, just for testing
gulp.task('inlinecriticalCSS', function(done) {
minimalcss
.minimize({ urls: ['http://localhost:9999/' + 'index.html'] })
.then(result => {
console.log('OUTPUT', result.finalCss.length, result.finalCss);
})
.catch(error => {
console.error(`Failed the minimize CSS: ${error}`);
});
done();
});
// webserver
gulp.task('serve', (done) => {
browserSync.init({
port: 9999,
server: {
baseDir: sourceDir
}
});
done();
});
// default sequence
gulp.task('default', gulp.series(
'prepare',
'build',
'serve',
'inlinecriticalCSS',
'cleanup')
);

gulp-connect developer server give no response when connect-history-api-fallback is used in middleware

I’m trying to use 'connect-history-api-fallback' with gulp-connect like this:
var gulp = require('gulp'),
connect = require('gulp-connect'),
historyApiFallback = require('connect-history-api-fallback');
gulp.task('server', function() {
connect.server({
root: 'app',
livereload: true,
middleware: function(connect, opt) {
return [ historyApiFallback ];
}
});
});
However, the server http://localhost:8080/ gives no response. No errors in the terminal, merely get timeout in browser.
When I remove middleware like bellow, everything is perfect:
gulp.task('server', function() {
connect.server({
root: 'app',
livereload: true
});
});
The API has changed.
The correct way of using connect-history-api-fallback now the following:
var gulp = require('gulp'),
connect = require('gulp-connect'),
historyApiFallback = require('connect-history-api-fallback');
gulp.task('server', function() {
connect.server({
root: 'app',
livereload: true,
middleware: function(connect, opt) {
return [ historyApiFallback({}) ];
}
});
});

Using browsersync as dev webserver combined with node app serving only api and not static files

I'm currently using gulp webserver with following config.
gulp.task('webserver', ['nodejs'], function () {
return gulp.src(config.client)
.pipe(webserver({
livereload: true,
port: 8001,
proxies: [
{
source: '/api',
target: 'http://localhost:3007/api'
}
],
directoryListing: false,
open: true
}));
});
So, it serves the static files and proxies request starting with /api to a nodeJs app on another port.
I want to do now the same with Browser-sync (instead of using livereload, so I want to get rid of gulp webserver), but don't find how I can configure this.
Thanks for giving some guidance.
Ok,I found a potential solution (please comment if you have improvements)
var browserSync = require('browser-sync');
var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer({});
gulp.task('bs', ['nodejs'], function () {
browserSync({
server: {
baseDir: "./client"
},
middleware: function (req, res, next) {
var url = req.url;
if (url.substring(0,5)==="/api/") {
proxy.web(req, res, { target: 'http://localhost:3007' });
} else {
next();
}
}
});
});

Gulp-connect shows an error 'listen EADDRINUSE'

I have a simple gulpfile.js:
var gulp = require('gulp');
var sass = require('gulp-sass');
var connect = require('gulp-connect');
var imagemin = require('gulp-imagemin');
var notify = require("gulp-notify");
var pngquant = require('imagemin-pngquant');
gulp.task('connect', function() {
connect.server({
root: ['./'],
livereload: true
});
});
gulp.task('sass', function() {
gulp.src(['css/**/*.scss'])
.pipe(sass({
errLogToConsole: false,
onError: function(err) {
return notify().write(err);
}
}))
.pipe(gulp.dest('build'))
.pipe(notify({ message: 'Styles task complete' }))
.pipe(connect.reload());
})
gulp.task('imagemin', function () {
return gulp.src('src/images/*')
.pipe(imagemin({
progressive: true,
svgoPlugins: [{removeViewBox: false}],
use: [pngquant()]
}))
.pipe(gulp.dest('build/images/'));
});
gulp.task('default', function() {
gulp.run('connect', 'sass', 'imagemin');
gulp.watch('css/**', function(event) {
gulp.run('sass');
gulp.run('connect');
})
gulp.watch('*.html', function(event) {
gulp.run('connect');
})
gulp.watch('src/images/*', function(event) {
gulp.run('imagemin');
})
})
gulp.task('start', ['connect']);
Livereload server works fine. However, when I try to edit scss or index.html files I'm getting the following error:
events.js:72
throw er; // Unhandled 'error'
^
Error: listen EADDRINUSE
at errnoException (net.js:904:11)
at Server._listen2 (net.js:1042:14)
at listen (net.js:1064:10)
at Server.listen (net.js:1138:5)
at ConnectApp.server (C:\xampp\htdo
ex.js:57:19)
at new ConnectApp (C:\xampp\htdocs\
js:37:10)
at Object.module.exports.server (C:
connect\index.js:170:12)
at Gulp.gulp.task.gulp.src.pipe.pip
smi2.0\gulpfile.js:10:11)
at module.exports (C:\xampp\htdocs\
rchestrator\lib\runTask.js:34:7)
at Gulp.Orchestrator._runTask (C:\x
de_modules\orchestrator\index.js:273:3)
Whithout gulp-connect everything works fine. I'm sure there is a small syntax error in gulpfile.js but I'm unable to find it. Please help to solve this out.
Here is a final gulpgile.js that works just fine thanx to #Rigotti:
var gulp = require('gulp');
var sass = require('gulp-sass');
var connect = require('gulp-connect');
var imagemin = require('gulp-imagemin');
var notify = require("gulp-notify");
var pngquant = require('imagemin-pngquant');
gulp.task('connect', function() {
connect.server({
root: ['./'],
livereload: true
});
});
gulp.task('sass', function() {
gulp.src(['css/**/*.scss'])
.pipe(sass({
errLogToConsole: false,
onError: function(err) {
return notify().write(err);
}
}))
.pipe(gulp.dest('build'))
.pipe(notify({ message: 'Styles task complete' }))
.pipe(connect.reload());
})
gulp.task('imagemin', function () {
return gulp.src('src/images/*')
.pipe(imagemin({
progressive: true,
svgoPlugins: [{removeViewBox: false}],
use: [pngquant()]
}))
.pipe(gulp.dest('build/images/'));
});
gulp.task('html', function () {
gulp.src('index.html')
.pipe(connect.reload());
});
gulp.task('default', function() {
gulp.run('connect', 'sass', 'imagemin');
gulp.watch('css/**', function(event) {
gulp.run('sass');
})
gulp.watch('*.html', function(event) {
gulp.run('html');
})
gulp.watch('src/images/*', function(event) {
gulp.run('imagemin');
})
})
gulp.task('start', ['connect']);
EADDRINUSE means that the port is already in use.
On the code below you're calling the connect task in default, but connect it's called again when you change your .sass files.
gulp.task('default', function() {
// server started
gulp.run('connect', 'sass', 'imagemin');
gulp.watch('css/**', function(event) {
gulp.run('sass');
gulp.run('connect'); // <-- problem! connect is already running!
});
...
So you're basically trying to listen to the same port you're using, giving you this error.
Remove the gulp.run('connect') inside the watchs and you're good to go.