Gulp Watch - gulp-nodemon - App Crashed - node.js

I'm trying to set up Gulp to watch 1 thing: server's source. Upon source update, the server node script will start over & client browser will refresh.
I believe I need gulp-nodemon for the server, while browser-sync for the client.
The server's script is executed by: node src\babel.js
The script works when ran that way, but fails through my config for Gulp.
Is there something I am doing wrong?
This is my task script:
var gulp = require('gulp');
var browserSync = require('browser-sync');
var nodemon = require('gulp-nodemon');
gulp.task('default', ['watchServer', 'watchClient']);
gulp.task('watchServer', function() {
gulp.watch('src/**', function () {
nodemon({ // called upon update
script: 'src/babel.js', // I have tried both / & \\
})
});
nodemon({ // called on start
script: 'src/babel.js', // I have tried both / & \\
})
});
gulp.task('watchClient', function() {
browserSync({
open: 'external',
host: '████████',
port: 80,
ui: false,
server: {
// We're serving the src folder as well
// for sass sourcemap linking
baseDir: ['src']
},
files: [
'src/**'
]
});
});
Log:
> gulp
[02:28:04] Using gulpfile B:\Test Server\gulpfile.js
[02:28:04] Starting 'watchServer'...
[02:28:04] Finished 'watchServer' after 19 ms
[02:28:04] Starting 'watchClient'...
[02:28:04] Finished 'watchClient' after 27 ms
[02:28:04] Starting 'default'...
[02:28:04] Finished 'default' after 9.66 μs
[02:28:04] [nodemon] 1.7.1
[02:28:04] [nodemon] to restart at any time, enter `rs`
[02:28:04] [nodemon] watching: *.*
[02:28:04] [nodemon] starting `node src\babel.js`
[BS] Access URLs:
-----------------------------------
Local: http://localhost:80
External: http://████████:80
-----------------------------------
[BS] Serving files from: src
[BS] Watching files...
events.js:141
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE :::80
at Object.exports._errnoException (util.js:837:11)
at exports._exceptionWithHostPort (util.js:860:20)
at Server._listen2 (net.js:1231:14)
at listen (net.js:1267:10)
at Server.listen (net.js:1363:5)
at B:/Test Server/src/app/app.jsx:17:7
at Object.<anonymous> (B:/Test Server/src/app/app.jsx:41:2)
at Module._compile (module.js:434:26)
at normalLoader (B:\Test Server\node_modules\babel-core\lib\api\register\node.js:199:5)
at Object.require.extensions.(anonymous function) [as .jsx] (B:\Test Server\node_modules\babel-core\lib\api\register\node.js:216:7)
[02:28:05] [nodemon] app crashed - waiting for file changes before starting...

You don't need to watch the server file with gulp since nodemon will automatically restart when it changes, try something like this in your config
gulp.task('watchServer', function() {
// remove the gulp.watch entry
nodemon({ // called on start
script: 'src/babel.js', // I have tried both / & \\
ext: 'js',
watch: ['src/babel.js']
})
});
There also seems to be something else running on port 80 (this is the default port for apache) so it might help to change the port browsersync is running on to something like 4000
If your node server is running on let's say port 3000 you will need to proxy it with browsersync for example.
gulp.task('watchClient', function() {
browserSync({
open: 'external',
host: '████████',
proxy: '[YOURHOST]:3000'
port: 4000,
ui: false,
// this entry will most likely need to be removed
// if you are using something like express as a static server
server: {
// We're serving the src folder as well
// for sass sourcemap linking
baseDir: ['src']
},
files: [
'src/**'
]
});
});

Related

BrowserSync on Docker is running correctly and able to detect changes, but browser doesn't seems to be triggered/reloaded

Source code can be found from: https://github.com/kevinchu-work/Docker_with_BrowserSync (Resolved & Completely working fine now)
I am trying a very simple Node Docker + BrowserSync + Gulp working together, but the browser never able to reload
Node: app.js
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.end('<h1>Hello World</h1><div>'+Math.random().toString(36)+'</div>');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
gulpfile.js: nodemon & browser-sync
'use strict';
var gulp = require('gulp');
var browserSync = require('browser-sync');
var nodemon = require('gulp-nodemon');
gulp.task('nodemon', function (cb) {
var started = false;
return nodemon({
script: 'app.js',
env: {
port: 3000
},
ignore: [
'gulpfile.js',
'node_modules/'
]
}).on('start', function () {
if (!started) {
started = true;
cb();
}
});
});
gulp.task('browser-sync', gulp.series(['nodemon'], function () {
// gulp.task('browser-sync', function () {
browserSync.init('*.js', {
open: false,
proxy: "localhost:3000",
// files: ["**/*.js"],
// port: 3000,
// notify: false
});
// });
}));
gulp.task('default', gulp.series('browser-sync', function () {
gulp.watch(["*.*"], function() { console.log("sync"); browserSync.reload; });
}));
startDocker: setup the docker
docker pull node
docker run -t -i -v $(pwd):/app -p 3000:3000 -p 3001:3001 -p:3002:3002 dev /bin/bash
Already, once the docker started & running, the following command trigger the node
cd /app
yarn install
yarn global add gulp
gulp
The node, nodemon running very well but the PORT shifted from 3000 to 3001 (ok, i can live with it), but it never trigger the refresh on browser side. I did open localhost:3001 and it running very well.
This is the output when running the previous command
root#5f80167a4a37:/project# gulp
[16:20:01] Using gulpfile /project/gulpfile.js
[16:20:01] Starting 'default'...
[16:20:01] Starting 'browser-sync'...
[16:20:01] Starting 'nodemon'...
[16:20:01] Finished 'nodemon' after 405 ms
[16:20:01] Starting '<anonymous>'...
[16:20:01] [nodemon] 2.0.4
[16:20:01] [nodemon] to restart at any time, enter `rs`
[16:20:01] [nodemon] watching path(s): *.*
[16:20:01] [nodemon] watching extensions: js,mjs,json
[16:20:01] [nodemon] starting `node app.js`
Server running at http://127.0.0.1:3000/
[Browsersync] Proxying: http://localhost:3000
[Browsersync] Access URLs:
-----------------------------------
Local: http://localhost:3001
External: http://172.17.0.2:3001
-----------------------------------
UI: http://localhost:3002
UI External: http://localhost:3002
-----------------------------------
[Browsersync] Watching files...
[16:21:14] [nodemon] restarting due to changes...
[16:21:14] [nodemon] starting `node app.js`
Server running at http://127.0.0.1:3000/
[Browsersync] Reloading Browsers...
The Browsersync did detect changes of files and execute reloading but browser. Any idea?

Gulp won't recompile sass when changes are made

I have created some tasks to recompile the sass with browser-sync whenever changes are made.
My gulp file is as follows:
'use strict';
var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync');
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: "./"
}
});
});
gulp.task('default', gulp.series('browser-sync', function() {
gulp.start('sass:watch');
}));
I am using node version 12.16.1, gulp-sass version 4.1.0, gulp-cli version 2.3.0, gulp local version 4.0.2 and browser-sync version 2.26.7.
Change this
// gulp.task('default', gulp.series('browser-sync', function() {
// gulp.start('sass:watch');
// }));
to
gulp.task('default', gulp.series('browser-sync', 'sass:watch'));
I seriously doubt that gulp v4 supports gulp.start.
Also change to this:
gulp.task('browser-sync', function(done) { // added done here
var files = [
'./*.html',
'./css/*.css',
'./img/*.{png,jpg,gif}',
'./js/*.js'
];
browserSync.init(files, {
server: {
baseDir: "./"
}
});
done(); // called done() here
});
When I ran your code I noticed that the sass:watch task was never starting, hence you were not watching any files at all. Here is what you should have seen in your terminal:
[21:26:21] Using gulpfile ~\OneDrive\Test Bed\simple\gulpfile.js
[21:26:21] Starting 'default'...
[21:26:21] Starting 'browser-sync'...
[21:26:21] Finished 'browser-sync' after 164 ms
[21:26:21] Starting 'sass:watch'... // this line missing when running your code
[Browsersync] Access URLs:
-----------------------------------
Local: http://localhost:3000
External: http://10.0.0.186:3000
-----------------------------------
UI: http://localhost:3001
UI External: http://localhost:3001
-----------------------------------
[Browsersync] Serving files from: ./
[Browsersync] Watching files...
Don't be fooled by the last line, browser-sync always spits that out. The reason why the sass:watch task was not starting was because gulp could never get past the browser-sync task - you have to signal gulp somehow that the task has completed and done is one way to do that. Then gulp can go to the next task, which was sass:watch. See gulp: async completion.
You also needed to make the change you noted in your comment gulp.watch('./css/*.scss', gulp.series('scss'));
There is nothing else wrong with your code - it runs perfectly fine for me.
Your Gulpfile isn't watching the sass files when changes are made. It's only looking for CSS changes. This is part of my Gulp task function to look for SCSS file changes
function serve() {
browserSync.init({
open: false,
port: 8000,
server: {
baseDir: 'src/',
index: 'index.html'
},
});
gulp.watch(paths.scss.src, gulp.series([compileSCSS]));
}
And this is my SCSS compile function
function compileSCSS() {
return gulp
.src('./src/scss/style.scss')
.pipe(plugins.rename('style.css'))
.pipe(gulp.dest('./src/css/'));
}
I have prepared a Gulp function with many required tools. You can check here
https://gist.github.com/choyan/ab034dc0539942ee0d8f0ab9788d790f

Can't get chrome to launch, using browser-sync

I have successfully written this code and it executes in bash, but doesn't launch the browser. Any help is appreciated.
Both the commented out code and the uncommented launch in bash fine, but I never get chrome to open my html file. How do get chrome to open? Am I missing something?
Toshiba Laptop#ToshibaLaptop MINGW64 ~/Desktop/Projects/trave-site (master)
$ gulp watch
[14:48:50] Using gulpfile ~\Desktop\Projects\trave-site\gulpfile.js
[14:48:50] Starting 'watch'...
[14:48:50] Finished 'watch' after 26 ms
[Browsersync] Access URLs:
-----------------------------------
Local: http://localhost:3000
External: http://10.0.0.235:3000
-----------------------------------
UI: http://localhost:3001
UI External: http://10.0.0.235:3001
-----------------------------------
[Browsersync] Serving files from: ./app
//gulp.task('browser-sync', function() { // this works if uncomented
// browserSync.init({
// server: {
// baseDir: "./"
// }
// });
//});
gulp.task('watch', function(){
browserSync.init({ // this works as well neither launch chrome
server : {
baseDir: "./app",
index: "index.html"
}
});
});

react project compiles but not working

I am on my reactjs project. I run gulp command to compile the project. During compile i get few errors and still the project compiles succcessfully. But I am not able to run my application. I am sure it is because of compile errors.
This is my compile console
Apurvs-MacBook-Pro:tessact-client-2 apurvgandhwani$ gulp
[01:52:51] Failed to load external module #babel/register
[01:52:51] Requiring external module babel-register
[01:52:54] Using gulpfile ~/Desktop/tessact-client-2/tessact-client-2/gulpfile.babel.js
[01:52:54] Starting 'build:watch'...
[01:52:54] Starting 'copy:assets'...
[01:52:54] Starting 'copy:vendors'...
Cleaned build/
Copied 14 asset entries.
[01:52:54] Finished 'copy:vendors' after 157 ms
[01:52:54] Starting 'copy:views'...
[01:52:54] copied views all files 1.79 kB
[01:52:54] Finished 'copy:views' after 60 ms
[01:52:54] Starting 'copy:public'...
[01:52:54] Finished 'copy:public' after 29 ms
[01:52:54] Finished 'copy:assets' after 248 ms
[01:52:54] Starting 'bundle:dll'...
DLL Bundled.
Hash: 0c28a0c5268f8a4b023c
Version: webpack 1.15.0
Time: 2362ms
Asset Size Chunks Chunk Names
dll.vendor.js 3.16 MB 0 [emitted] vendor
[01:52:57] Finished 'bundle:dll' after 2.4 s
[01:52:57] Starting 'bundle'...
Hash: d2622522a127e8235b84
Version: webpack 1.15.0
Time: 641ms
Asset Size Chunks Chunk Names
server-bundle.js 65 kB 0 [emitted] main
-- server:watch bundled.
Hash: b86595a12c8058d77ded
Version: webpack 1.15.0
Time: 6049ms
Asset Size Chunks Chunk Names
00103e881a36640a08f869ff6888f0fd.eot 5.9 kB [emitted]
main-bundle.js 3.13 MB 0 [emitted] main
-- client bundled.
[01:53:03] Finished 'bundle' after 6.05 s
[01:53:03] Starting 'start:server'...
Starting Node Server...
[01:53:03] Finished 'start:server' after 147 ms
[01:53:03] Starting 'watch:sync'...
[01:53:03] [nodemon] 1.14.11
[01:53:03] [nodemon] to restart at any time, enter `rs`
[01:53:03] [nodemon] watching: build/server-bundle.js
[01:53:03] [nodemon] starting `node --debug --inspect build/server-bundle.js`
Server Restarted: Reloading BrowserSync.
Debugger listening on ws://127.0.0.1:9229/c6e6fdcb-9801-4097-b9cb-7480c39f4380
For help see https://nodejs.org/en/docs/inspector
[tessact: ] Proxying: http://localhost:4200
[tessact: ] Access URLs:
-------------------------------------
Local: http://localhost:3000
External: http://192.168.0.32:3000
-------------------------------------
UI: http://localhost:3001
UI External: http://192.168.0.32:3001
-------------------------------------
[tessact: ] Watching files...
[01:53:03] Finished 'watch:sync' after 224 ms
[01:53:03] Starting 'watch:assets'...
[01:53:03] Finished 'watch:assets' after 14 ms
[01:53:03] Finished 'build:watch' after 9.09 s
[01:53:03] Starting 'default'...
[01:53:03] Finished 'default' after 28 μs
tessact:db DBERROR: connect ECONNREFUSED 127.0.0.1:3306 +0ms
ServerStartupError: { Error: connect ECONNREFUSED 127.0.0.1:3306
at Object._errnoException (util.js:1003:13)
at _exceptionWithHostPort (util.js:1024:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1194:14)
at Protocol._enqueue (/Users/apurvgandhwani/Desktop/tessact-client-2/tessact-client-2/node_modules/mysql/lib/protocol/Protocol.js:145:48)
at Protocol.handshake (/Users/apurvgandhwani/Desktop/tessact-client-2/tessact-client-2/node_modules/mysql/lib/protocol/Protocol.js:52:23)
at Connection.connect (/Users/apurvgandhwani/Desktop/tessact-client-2/tessact-client-2/node_modules/mysql/lib/Connection.js:130:18)
at /Users/apurvgandhwani/Desktop/tessact-client-2/tessact-client-2/build/webpack:/src/server/db.js:26:14
From previous event:
at initDB (/Users/apurvgandhwani/Desktop/tessact-client-2/tessact-client-2/build/webpack:/src/server/db.js:25:9)
at Object.defineProperty.value (/Users/apurvgandhwani/Desktop/tessact-client-2/tessact-client-2/build/webpack:/src/server/app.js:27:1)
at __webpack_require__ (/Users/apurvgandhwani/Desktop/tessact-client-2/tessact-client-2/build/webpack:/webpack/bootstrap d2622522a127e8235b84:19:1)
at Object.<anonymous> (/Users/apurvgandhwani/Desktop/tessact-client-2/tessact-client-2/build/server-bundle.js:48:19)
at __webpack_require__ (/Users/apurvgandhwani/Desktop/tessact-client-2/tessact-client-2/build/webpack:/webpack/bootstrap d2622522a127e8235b84:19:1)
at /Users/apurvgandhwani/Desktop/tessact-client-2/tessact-client-2/build/webpack:/webpack/bootstrap d2622522a127e8235b84:39:1
at Object.<anonymous> (/Users/apurvgandhwani/Desktop/tessact-client-2/tessact-client-2/build/server-bundle.js:44:10)
at Module._compile (module.js:660:30)
at Object.Module._extensions..js (module.js:671:10)
at Module.load (module.js:573:32)
at tryModuleLoad (module.js:513:12)
at Function.Module._load (module.js:505:3)
at Function.Module.runMain (module.js:701:10)
at startup (bootstrap_node.js:193:16)
at bootstrap_node.js:617:3
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 3306,
fatal: true }
[tessact: ] Reloading Browsers...
[01:53:05] [nodemon] clean exit - waiting for changes before restart
webpack built b86595a12c8058d77ded in 3199ms
Hash: b86595a12c8058d77ded
Version: webpack 1.15.0
Time: 3199ms
Asset Size Chunks Chunk Names
00103e881a36640a08f869ff6888f0fd.eot 5.9 kB [emitted]
main-bundle.js 3.13 MB 0 main
webpack: Compiled successfully.
There is an error in the starting and one in the middle of the snippet.
This is my config.js file
const IS_PROD = (process.env.NODE_ENV === "production");
// const IS_PROD = false;
const NODE_PORT = 4211;
const BS_PORT = 3002;
module.exports = {
NODE_PORT,
BS_PORT,
SESSION_SECRET: 't355#c7_S3cr37',
LOGIN_URL: "https://www.backend.trigger.tessact.com/auth/login/",
DB: {
production: {
host: 'localhost',
port: 3306,
user: 'root',
password: '',
database: 'tessact_db'
},
development: {
host: 'localhost',
port: 3306,
user: 'root',
password: '',
database: 'tessact_db'
}
},
ACL_POPULATION_URL: '/populate',
ACL_UPDATE_URL: '/update-acl-population'
}
This is my configure.js file
import express from 'express'
import path from 'path'
import favicon from 'serve-favicon'
import logger from 'morgan'
import cookieParser from 'cookie-parser'
import bodyParser from 'body-parser'
import compression from 'compression'
import session from 'express-session'
import config from './config'
import getRoutes from './routes'
const IS_PROD = process.env.NODE_ENV === 'production';
export default function configureServer(db, app){
const loggerMode = IS_PROD ? 'combined' : 'dev'
const env = IS_PROD ? 'production' : 'development'
const MySQLStore = require('express-mysql-session')(session)
app.set('env', env);
app.use(logger(loggerMode));
// Pretty prints template output
if (!IS_PROD) {
app.locals.pretty = true;
}
// Where to find templates
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(compression());
// Server static assets from this directory
app.use('/public',
express.static( path.resolve(__dirname, './public'))
);
// Should come after static assets
// Otherwise static requests will be treated with cookies and session as well
app.use(cookieParser(config.SESSION_SECRET));
app.use(
session({
resave: true,
saveUninitialized: true,
secret: config.SESSION_SECRET,
store: new MySQLStore({}, db)
})
)
// Add routes
app.use('/', getRoutes(db, app));
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
return Promise.resolve({db, app})
}
This is my db.js
import Promise from 'bluebird';
import config from './config';
import mysql from 'mysql';
var debug = require('debug')('tessact:db');
const IS_PROD = (process.env.NODE_ENV !== "production");
const connOptions = config.DB[
IS_PROD ? 'production' : 'development'
]
var connection = mysql.createConnection(connOptions)
process.on('SIGTERM', ()=> {
connection.end(err=> {
if (error){
console.error(err);
}
debug('DB Closed');
})
});
const initDB = ()=> {
return new Promise((resolve, reject)=>{
connection.connect(err => {
if (err){
debug('DBERROR: ', err.message)
return reject(err)
}
debug('Connected')
resolve(connection)
})
});
}
export default initDB;
Your application fails to connect to the database (I assume mysql). It tries to connect to localhost:3306 and gets connect ECONNREFUSED 127.0.0.1:3306 which usually means there is no mysql listening on this server.
You should either start mysql on the same machine, or configure your application to connect to a remote mysql.
It is also possible that you have a database running but listening on a different port or network-interface.

Using browser-sync with node.js app

I have an existing node app. My Node directory structure is setup like this:
./
node_modules/
src/
views/
index.html
...
server.js
test/
gulpfile.js
package.json
I can successfully start my app my running node ./src/server.js from the root shown above. Once started, I can visit "http://localhost:3000" in the browser and see the contents of index.html like I am expecting.
I want to speed up my development and I recently learned about browsersync. In an attempt to include it in my gulp process, I have the following:
var browserSync = require('browser-sync').create();
browserSync.init({
server: {
baseDir: './src/',
server: './src/server.js'
}
});
When I run gulp, I see the following in the command-line:
BS] Access URLs:
--------------------------------------
Local: http://localhost:3000
External: http://[ip address]:3000
--------------------------------------
UI: http://localhost:3001
UI External: http://[ip address]:3001
--------------------------------------
My browser is then opened and it attempts to load http://localhost:3000. At this point, I see the following error in the browser window:
Cannot GET /
What am I doing wrong? I can successfully visit http://localhost:3000 if I start my app using node ./src/server.js, however, its like its not running with BrowserSync. What am I doing wrong?
You already have a node server so i think what you need is Proxy.
And i would also suggest you to use nodemon for going one step ahead in your speed up development thing. It will automatically restart your node development server in case of any changes. So a sample gulpfile in your case(with nodemon) might look like
var gulp = require('gulp');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var nodemon = require('gulp-nodemon');
gulp.task('browser-sync', ['nodemon'], function() {
browserSync.init(null, {
proxy: "http://localhost:3700", // port of node server
});
});
gulp.task('default', ['browser-sync'], function () {
gulp.watch(["./src/views/*.html"], reload);
});
gulp.task('nodemon', function (cb) {
var callbackCalled = false;
return nodemon({script: './src/server.js'}).on('start', function () {
if (!callbackCalled) {
callbackCalled = true;
cb();
}
});
});
~
Why do you want to use the built-in server if you have your own in ./src/server.js ?
Check this, What server in browsersync does is create a static server for basic HTML/JS/CSS websites, so you might need to use the proxy feature as shown here.
This means that you need to run your server as normally and wrap it up in the proxy.
Using the express generator default folder structure with the start script in bin\www, and using the ejs template, this is how i modified my gulpfile.js :
var gulp = require('gulp');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var nodemon = require('gulp-nodemon');
gulp.task('browser-sync', ['nodemon'], function() {
browserSync.init(null, {
proxy: "http://localhost:8000", // port of node server
});
});
gulp.task('default', ['browser-sync'], function () {
gulp.watch(["./views/*.ejs"], reload);
});
gulp.task('nodemon', function (cb) {
var callbackCalled = false;
return nodemon({
script: './bin/www',
env: {
PORT: 8000
}}).on('start', function () {
if (!callbackCalled) {
callbackCalled = true;
cb();
}
});
});
Notice that am watching for any files that end in .ejs. I also got a problem when using nodemon with the port in use, so i added an env to pass the port as 8000,
env: { PORT: 8000 }
Since the tag grunt is missing from the question, here's a solution that works using only NPM (package.json):
"scripts": {
"start": "browser-sync start --serveStatic 'src' --serveStatic 'node_modules' --files 'src'"
}
Now all the <script> src attributes can be relative:
<script src="/stats-js/build/stats.min.js"></script>

Resources