How do I kill browserSync before creating it? - browser-sync

Before executing "var bs = browserSync.create();", I would like to kill browserSync if a browserSync process is running.
Is it correct that exit() method needs a browsersync instance? (
https://www.browsersync.io/docs/api#api-exit)
What is the best way ?
//A gulp script
var browserSync = require('browser-sync');
//Step 1 --- Kill browsersync
?
//Step2 --- Start browsersync
var bs = browserSync.create();

reference from the documentation
var bs = require("browser-sync").create();
console.log(bs.active); // will return true/false whether browserSync is running or not
if(bs.active) {
bs.exit();
} else {
bs.init(config, function (err, bs) {
// -> now true since BS is running now
console.log(bs.active);
});
}

Related

How do you use event-stream to pause and resume Gulp streams?

I'm trying clone npm packages to a client-side location, so I have created multiple streams to accomplish this and merge them to return from gulp.task(). However, it is my understanding that I will need to pause the streams in order for the task to receive the proper exit.
The following code runs without error, but if I comment the return line. One of the packages is still copied, when I would expect none of the streams to reach their gulp.dest(). Why aren't all the streams paused?
var gulp = require('gulp')
, eventStream = require('event-stream')
;
const projects = {
src: {
dependencies: {
codemirror: './src/lib/codemirror',
acorn: './src/lib/acorn'
}
}
};
gulp.task('init:client-packages', function () {
let streams = []
, ps = eventStream.pause();
// Load project client-side dependencies
for (let prj in projects) {
for (let pkg in projects[prj].dependencies) {
streams.push(
gulp.src('./node_modules/' + pkg + '/**')
.pipe(ps)
.pipe(gulp.dest(projects[prj].dependencies[pkg]))
);
}
}
// Merge source streams
return eventStream.merge(streams).pipe(ps.resume());
// ^^ Commenting this line doesn't block gulp.dest() from completing.
});
There maybe a bug in event-stream as the following code only works with merge-stream.
var merge = require('merge-stream')
, eventStream = require('event-stream')
;
gulp.task('init:client-packages', function() {
let streams = [];
// Load project client-side dependencies
for (let prj in projects) {
for (let pkg in projects[prj].dependencies) {
streams.push(
gulp.src('./node_modules/' + pkg + '/**')
.pipe(gulp.dest(projects[prj].dependencies[pkg]))
);
}
}
// Merge source streams
return merge(streams);
// --OR--
return eventStream.merge(streams); // Results in message below.
});
As stated above event-stream doesn't close the task properly. The output is as follows:
[23:36:46] Starting 'init:client-packages'...
[23:36:47] The following tasks did not complete: init:client-packages
[23:36:47] Did you forget to signal async completion?
Process terminated with code 1.

Debugging gulp task is very slow to hit first breakpoint

I have a gulp task I am debugging but to hit the first break point takes a really long time.
This is how I debug my task
node-debug gulp taskName
It brings up chrome and it takes about 30 seconds to hit my break point. I want to note that my gulp file and code I am trying to debug is very small and a very light weight.
I figured out the issue.
My gulp file has globally defined requires at the top for other tasks on the file.
//var browserSync = require('browser-sync').create();
//var foreach = require('gulp-foreach');
//var fileList = require('gulp-filelist');
//var gp_concat = require('gulp-concat');
//var gp_rename = require('gulp-rename');
//var gp_uglify = require('gulp-uglify');
//var browserSync = require('browser-sync').create();
//var watch = require('gulp-watch');
//var removeFiles = require('gulp-remove-files');
//var fs = require('fs');
While my task did not use them they still were initialized and therefore added to the debugging load time. What I will do is define them where ever I need them.

How to make a child powershell process on node

I'm trying to have a spawned Powershell process on Windows with NodeJS, which i can send some commands, and the the output. I've did that with the stdio configuration form the parent node process, but i want to have it separated, and i cant achieve any of this to correctly work.
In this code, i was hoping to get the output of $PSTableVersion powershell variable on the psout.txt file, but it gets never written.
The simple code is:
var
express = require('express'),
fs = require('fs'),
spawn = require("child_process").spawn;
var err = fs.openSync('pserr.txt', 'w');
var out = fs.openSync('psout.txt', 'w');
var writer = fs.createWriteStream(null, {
fd: fs.openSync('psin.txt', 'w')
});
var child = spawn("powershell.exe", ["-Command", "-"], {
detached: true,
stdio: [writer, out, err]
});
writer.write('$PSTableVersion\n');
writer.end();
child.unref();
// just wait
var app = express();
app.listen(3000);
Update
I've tried with the code on this node github issue tracker: https://github.com/joyent/node/issues/8795
It seems calling .NET vs calling native executable are different things...

How to test a clustered Express app with Mocha?

Here is a simplified version of my cluster Express app:
/index.js
module.exports = process.env.CODE_COV
? require('./lib-cov/app')
: require('./lib/app');
/lib/app.js
var cluster = require('cluster'),
express = require('express'),
app = module.exports = express.createServer();
if (cluster.isMaster) {
// Considering I have 4 cores.
for (var i = 0; i < 4; ++i) {
cluster.fork();
}
} else {
// do app configurations, then...
// Don't listen to this port if the app is required from a test script.
if (!module.parent.parent) {
app.listen(8080);
}
}
/test/test1.js
var app = require('../');
app.listen(7777);
// send requests to app, then assert the response.
Questions:
var app = require('../'); will not work in this cluster environment. Which of the worker apps should it return? Should it return the cluster object instead of an Express app?
Now, obviously setting the port in the test script will not work. How would you set a port within a test script to a cluster of apps?
How would you send requests to this cluster of apps?
The only solution I can think of is to conditionally turn off the clustering feature and run only one app if the app is requested from a test script (if (module.parent.parent) ...).
Any other way to test a clustered Express app with Mocha?
It's been quite a long time since I have posted this question. Since no one has answered, I will answer to this question myself.
I kept the /index.js as it is:
module.exports = process.env.CODE_COV
? require('./lib-cov/app')
: require('./lib/app');
In /lib/app.js which starts the cluster, I have the following code. In brief, I start the cluster only in non-test environment. In test environment the cluster is not started but only one app/worker itself is started as defined in the cluster.isMaster && !module.parent.parent condition.
var cluster = require('cluster'),
express = require('express'),
app = module.exports = express.createServer();
if (cluster.isMaster && !module.parent.parent) {
// Considering I have 4 cores.
for (var i = 0; i < 4; ++i) {
cluster.fork();
}
} else {
// do app configurations, then...
// Don't listen to this port if the app is required from a test script.
if (!module.parent.parent) {
app.listen(8080);
}
}
In the above case !module.parent.parent will be evaluated as a truthful object only if the application was not started by a test script.
module is the current /lib/app.js script.
module.parent is its parent /index.js script.
module.parent.parent is undefined if the application was started directly via node index.js.
module.parent.parent is the test script if the application was started via one of the scripts.
Thus, I can safely start the script where I can set a custom port.
/test/test1.js
var app = require('../');
app.listen(7777);
// send requests to app, then assert the response.
At the same time if I need to run the application in real, i.e. not for testing, then I run node index.js and it will start up the cluster of applications.
I have a much simpler way of doing this
if (process.env.NODE_ENV !== 'test') {
if (cluster.isMaster) {
var numCPUs = require('os').cpus().length;
console.log('total cpu cores on this host: ', numCPUs);
for (var i = 0; i < numCPUs; i++) {
console.log('forking worker...');
cluster.fork();
}
cluster.on('online', function(worker) {
console.log('Worker ' + worker.process.pid + ' is online.');
});
cluster.on('exit', function(worker, code, signal) {
console.log('worker ' + worker.process.pid + ' died.');
});
} else {
console.log('Im a worker');
// application code
setupServer()
}
} else {
// when running tests
setupServer();
}
Just make sure to set the env to test when running the tests
ex: NODE_ENV=test grunt test
I kind of liked your solution because of it's simplicity, however, in an environment like an MVC framework for node, you may end up chaining module.parent up to 11 times (seriously).
I think a better approach would be to simply check which script node started processing with. The node's command-line arguments are available at process.argv.
The first item in this array would be 'node', the executable and the second argument would be the path to the file that node start executing. This would be index.js in your case.
So instead of checking
module.parent.parent
^ ^
(app.js) |
(index.js)
You could do something like this
var starter = process.argv[1].split(path.sep).pop();
Where starter would be index or index.js depending on what you started your server with.
node index.js vs node index
The check would then look like:
if (cluster.isMaster && starter === 'index.js') {
cluster.fork();
}
Worked in my environments—I hope this helps!

Assert inner function called

I have a file foo.js that looks like this:
var exec = require('child_process').exec
...
function start(){
...
exec('open -g http://localhost:<port>'); // opens a browser window
}
// EOF
I want to test that when I call the start() function, a browser window gets opened. Ideally, I'd like to use Sinon to stub out exec (so that we don't actually open a browser window during automated tests), and assert that exec was called. I've tried many ways, none of which work. For example in foo_test.js:
var subject = require('../lib/foo');
describe('foo', function(){
describe('start', function(){
it('opens a browser page to the listening address', function(){
var stub = sinon.stub(subject, 'exec', function(){
console.log('stubbed exec called');
}); // fails with "TypeError: Attempted to wrap undefined property exec as function"
});
});
});
How would I go about doing this?
Not sure if this is what you're looking for, but a quick search returned:
https://github.com/arunoda/horaa
Basically, it allows you to stub out libraries. From the examples:
Your Code
//stored in abc.js
exports.welcome = function() {
var os = require('os');
if(os.type() == 'linux') {
return 'this is a linux box';
} else {
return 'meka nam linux nemei :)';
}
};
Test Code (note the mocking of OS)
//stored in test.js
var horaa = require('horaa');
var lib = require('./abc'); // your code
var assert = require('assert');
//do the hijacking
var osHoraa = horaa('os');
osHoraa.hijack('type', function() {
return 'linux';
});
assert.equal(lib.welcome(), 'this is a linux box');
//restore the method
osHoraa.restore('type');
Hope that helps.

Resources