Erin Geyer Erin Geyer - 8 days ago 9
Node.js Question

Get BrowserSync external URL programmatically in Gulp file so I can pass it to an external node script?

I want to be able to send the browserSync external URL as a parameter for an external node script in my gulp file. How can I get at that external URL through the browserSync object (or some other way)?

var gulp = require('gulp');
var shell = require('gulp-shell');
var browserSync = require('browser-sync').create();

gulp.task('default', ['browser-sync', 'config']);

gulp.task('browser-sync', function() {
browserSync.init({
proxy: "localhost:8024",
open: "external"
});
});

gulp.task('config', shell.task([
"node scripts/someNodeScript.js browserSync.externalURL"
]));





UPDATE

Based on the excellent answer by @sven-shoenung below, I slightly tweaked his solution and am successfully using this:

var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var spawn = require('child_process').spawn;

var externalUrl;

var browserSyncDone = function () {
spawn('node', ['scripts/someNodeScript.js', externalUrl], {stdio:'inherit'});
};

gulp.task('default', ['browser-sync']);

gulp.task('browser-sync', function() {
browserSync.init({
proxy: "localhost:8024",
open: "external"
}, function() {
externalUrl = browserSync.getOption('urls').get('external');
browserSyncDone();
});
});

Answer

You can use browserSync.getOptions('urls') to get a Map of all access URLs. It returns something like this:

Map { 
  "local": "http://localhost:3000", 
  "external": "http://192.168.0.125:3000", 
  "ui": "http://localhost:3001",  
  "ui-external": "http://192.168.0.125:3001" 
}

Note that is only available after browser-sync is successfully initialized, so you need to pass a callback function to browserSync.init() or you'll try to get the value too soon.

You won't be able to use gulp-shell for the same reason. shell.task() will be set up before browser-sync has initialized, so browserSync.getOptions('urls') isn't available yet.

I recommend you use the standard nodejs child_process.spawn() instead.

var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var spawn = require('child_process').spawn;

var externalUrl;

gulp.task('default', ['browser-sync', 'config']);

gulp.task('browser-sync', function(done) {
  browserSync.init({
    proxy: "localhost:8024",
    open: "external"
  }, function() {
    externalUrl = browserSync.getOption('urls').get('external');
    done();
  });
});

gulp.task('config', ['browser-sync'], function(done) {
  spawn('node', ['scripts/someNodeScript.js', externalUrl], {stdio:'inherit'}).on('close', done);
});