I have a gulp task running with browser-sync,by default its running on port 3000 of node.js server.I want to change the default port to any other port like 3010.
var gulp = require('gulp'),
connect = require('gulp-connect'),
browserSync = require('browser-sync');
gulp.task('serve', [], function() {
browserSync(
{
server: "../ProviderPortal"
});
});
/*** 8. GULP TASKS **********/
gulp.task('default', ['serve']);
I am using:
browser-sync version-2.6.1
I tried configuring the gulp task like:
gulp.task('serve', [], function() {
browserSync(
{
ui: {
port: 8080
},
server: "../ProviderPortal"
});
});
But it didnot work.
Answer based on the documentation links (link1, link2).
You are using browser-sync version 2.0+, they have a different recommended syntax. Using that syntax your code could be like this:
// require the module as normal
var bs = require("browser-sync").create();
....
gulp.task('serve', [], function() {
// .init starts the server
bs.init({
server: "./app",
port: 3010
});
});
You specify required port directly in configuration object.
Related
I'm running a development livereload server with gulp-server-livereload. This is the default task in gulpfile.js
var gulp = require('gulp');
var server = require('gulp-server-livereload');
gulp.task('default', function() {
gulp.src(basePath)
.pipe(server({
livereload: true,
host: domain,
port: 80,
}));
});
Then there's another task, gulp export, which requires this running web server. If I start another one it gives an error (because the ports 80 and 35729 are busy). So the logic I'm going for is this:
if gulp default is already running, dive right into nightmare.js tasks
else start a server and proceed to nightmare.js tasks
So my problem is I don't know a robust way to check if a gulp task is running.
Can I do that with some Gulp method? Or from the level of Node?
I wouldn't like to check open ports or webserver address as a proxy for "yes default task is running" if at all possible.
Can I do that with some Gulp method? Or from the level of Node? I wouldn't like to check open ports or webserver address as a proxy for "yes default task is running" if at all possible.
I have found no gulp way so far, so here is checking for ports busy. If they are it infers the server is running and proceeds with the export tasks, if not it starts a server.
var server = require('gulp-server-livereload');
gulp.task('export', function () {
var net = require('net');
var portFree = function(port, callback) {
var server = net.createServer(function(socket) {
socket.write('Echo server\r\n');
socket.pipe(socket);
});
server.listen(port, '127.0.0.1');
server.on('error', function (e) {
callback(false);
});
server.on('listening', function (e) {
server.close();
callback(true);
});
};
portFree(35729, function(returnValue) {
// If server isn't already running, start it.
if(returnValue) {
gulp.src(basePath)
.pipe(server({
livereload: true,
host: 'http://localhost'
}));
}
});
// Do the actual export tasks...
});
I am using gulp-nodemon because of its most obvious of utilities.
Nodemon is a utility that will monitor for any changes
in your source and automatically restart your server.
But I am not understanding a practice which seems to be prevalent in express/node development.
I just started working with node and express but from what I understand:
app.js
var express = require('express'),
app = express(),
port = process.env.PORT || 8016;
app.get('/', function rootHndlr(req, res) {
/* body... */
res.send('welcome to my API!');
});
app.listen(port, function listenHndlr(){
console.log('Gulp is running my app on PORT ' + port);
});
The following is setting in the port to 8016 if not set.
port = process.env.PORT || 8016;
So now we binds and listens for connections on the specified host and port.
But then I see people configure in their gulp tasks the following to nodemon in their gulpfile.js
gulpfile.js
var gulp = require('gulp'),
nodemon = require('gulp-nodemon');
gulp.task('default', function() {
// content
nodemon({
script: 'app.js',
ext: 'js'
env: {
PORT: 8000
},
ignore: ['./node_modules/**']
}).
on('restart', function(){
consile.log('Restarting');
});
});
As you can one of the values in nodemon env: {PORT: 8000} Why set the port again?
Thanks!
People are using something like that as a fallback: port = process.env.PORT || 8016;
Your application should be flexible enough and by passing an env var to make it listen to another port. In general, this is the purpose of the env vars.
About your example, I suppose that there is a reason that the guy that wrote this gulpfile would like to make the app listen to port 8000. I would say that it is safe to change the value or to remove the PORT: 8000 as soon as you are 100% sure that there is no reason that the application needs to run on port 8000 (for example, it is behind a reverse proxy that forwards the traffic to port 8000).
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>
Hi I have some architecture, My front end application I have built using grunt,it running on localhost:3000 nodejs server, My BackEnd Application are in the Apache tomcat server (localhost:8080) . Basically backend application running on spring framework. guys i want to send request from my localhost:3000 to localhost:8080 using gruntjs.
Pls help me.
This is my grunt js file
module.exports = function(grunt){
grunt.initConfig({
concat: {
options: {
separator : '\n\n//--------------------------------------------------\n\n;',
banner : '\n\n//---------------All Js file is here ---------------\n\n'
},
dist :{
src :['components/scripts/*.js'],
dest:'builds/development/js/scripts.js'
}
},
sass : {
dist :{
options:{
style:'expanded'
},
files:[{
src:'components/sass/style.scss',
dest:'builds/development/css/style.css'
}]
}
},
connect:{
server:{
options:{
hostname:'localhost',
port:'3000',
base:'builds/development/',
livereload:true
}
}
},
watch: {
scripts: {
files: ['builds/development/**/*.html',
'components/scripts/**/*.js',
'components/sass/**/*.scss'],
tasks: ['concat','sass'],
options: {
spawn: false,
livereload:true
},
},
}
});
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-sass');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.registerTask('default',['concat','sass','connect','watch']);
};
To solve your problem you have to write separate node server and register with grunt task.
var http = require('http');
var httpProxy = require('http-proxy');
var server = http.createServer(function(){
httpProxy.createProxyServer({target: 'http://localhost:8080'}).web(req, res);
});
module.exports = function(grunt) {
grunt.registerTask('server', function() {
// this.async(); // run forever
server.listen(8000);// Front End Server Listening Port
});
};
I have written an application in Node.js (with Express & socket.io) and I would like to use Grunt to compile my client-side stuff with livereload while developing and being connected to Node.js application. How can I do this? (Preferably without running Node.js app in another port and client in another port, because of pathing and cross-domain issues)
I installed also Yeoman and it's using out of the box grunt-contrib-livereload package, but from what I understood it's using Node.js Connect server for serving client-side files, thus being separated from my Node.js application..
Example from Gruntfile.js generated by Yeoman:
var lrSnippet = require('grunt-contrib-livereload/lib/utils').livereloadSnippet;
var mountFolder = function (connect, dir) {
return connect.static(require('path').resolve(dir));
};
// ... cut some parts
grunt.initConfig({
watch: {
livereload: {
files: [
'<%= yeoman.app %>/*/*.html',
'{.tmp,<%= yeoman.app %>}/styles/*.css',
'{.tmp,<%= yeoman.app %>}/scripts/*.js',
'<%= yeoman.app %>/images/*.{png,jpg,jpeg}'
],
tasks: ['livereload']
}
// ..cut some parts
},
connect: {
livereload: {
options: {
port: 9000,
middleware: function (connect) {
return [
lrSnippet,
mountFolder(connect, '.tmp'),
mountFolder(connect, 'app')
];
}
}
}
}
// ..cut some parts
});
grunt.registerTask('server', [
'clean:server',
'coffee:dist',
'compass:server',
'livereload-start',
'connect:livereload',
'open',
'watch'
]);
Not sure if you have solved this question yet, but I have done this by adding my express application as a middleware attached to the 'connect.livereload.options.middleware' option.
However, automatic reloading of server side code doesn't work. For that you could implement a reload friendly server using a simple 'node ./server.js', create a connect middleware that acts as a transparent proxy to your development server, and invoke that within your Gruntfile.js before your standard connect/livereload server starts.
connect: {
options: {
port: 9000,
// change this to '0.0.0.0' to access the server from outside
hostname: 'localhost'
},
livereload: {
options: {
middleware: function (connect) {
return [
lrSnippet,
mountFolder(connect, '.tmp'),
mountFolder(connect, 'app'),
require('./server') // your server packaged as a nodejs module
];
}
}
}
}
server.js:
var app = express();
...
// Export your server object.
module.exports = app;
My answer is using Gulp that I am more familiar with, instead of Grunt, but I imagine the same approach would work with Grunt as well.
See my repository (and an older one) and my other answer.
Neither any browser extension nor adding any script to your files is needed.
The solution is based on the gulp-livereload and connect-livereload packages working together. First, you start your live reload listener, and pipe into it any file changes (change * to any more specific node-glob to listen to only specific files):
var gulpLivereload = require('gulp-livereload');
gulpLivereload.listen();
gulp.watch('*', function(file) {
gulp.src(file.path)
.pipe(gulpLivereload());
});
Second, you configure your server to use the listener as middleware via connect-livereload:
var connect = require('connect');
var connectLivereload = require('connect-livereload');
connect()
.use(connectLivereload())
.use(connect.static(__dirname))
.listen(8080);
See the packages for more information on how they work internally.
In the Gruntfile, remove connect:livereload and open from server task.
Add following script in the HTML file
<!-- livereload script -->
<script type="text/javascript">
document.write('<script src="http://'
+ (location.host || 'localhost').split(':')[0]
+ ':35729/livereload.js?snipver=1" type="text/javascript"><\/script>')
</script>