use grunt to restart a phantomjs process - javascript

I'm using grunt to have some tasks done every time I change my code ( jshint for example ) and I want to reload a phantomJs process every time I have changes.
The first way I found is to use grunt.util.spawn to run phantomJs the first time.
// http://gruntjs.com/api/grunt.util#grunt.util.spawn
var phantomJS_child = grunt.util.spawn({
cmd: './phantomjs-1.9.1-linux-x86_64/bin/phantomjs',
args: ['./phantomWorker.js']
},
function(){
console.log('phantomjs done!'); // we never get here...
});
And then, every time watch restarts, another task uses grunt.util.spawn to kill the phantomJs process, which is of course VERY ugly.
Is there any better way to do it?
The thing is that the phantomJs process is not teminating because I use it as a webserver to server a REST API with JSON.
Can I have a grunt callback or something whenever watch kicks in so I can close my previous phantomJs process before I re-run the task to create a new one?
I used grunt.event to make a handler, but I cannot see how to access the phantomjs process in order to kill it.
grunt.registerTask('onWatchEvent',function(){
// whenever watch starts, do this...
grunt.event.on('watch',function(event, file, task){
grunt.log.writeln('\n' + event + ' ' + file + ' | running-> ' + task);
});
});

This entirely untested code could be a solution for your problem.
Node's native child spawning function exec immediately returns a reference to the child process, which we can keep around to later kill it. To use it we can create a custom grunt task on the fly, like so:
// THIS DOESN'T WORK. phantomjs is undefined every time the watcher re-executes the task
var exec = require('child_process').exec,
phantomjs;
grunt.registerTask('spawn-phantomjs', function() {
// if there's already phantomjs instance tell it to quit
phantomjs && phantomjs.kill();
// (re-)start phantomjs
phantomjs = exec('./phantomjs-1.9.1-linux-x86_64/bin/phantomjs ./phantomWorker.js',
function (err, stdout, stderr) {
grunt.log.write(stdout);
grunt.log.error(stderr);
if (err !== null) {
grunt.log.error('exec error: ' + err);
}
});
// when grunt exits, make sure phantomjs quits too
process.on('exit', function() {
grunt.log.writeln('killing child...');
phantomjs.kill();
});
});

Related

Can I gulp-notify when a watched task completes?

We have a gulpfile with ~12 tasks, 4 of which are activated by a gulp.watch. I would like to use gulp-notify when a task started by gulp.watch completes. I don't want gulp-notify to do anything if a task is run directly. Sample code below:
const
debug = require("gulp-debug"),
gulp = require("gulp"),
notify = require("gulp-notify");
gulp.task("scripts:app", function () {
return gulp.src(...)
.pipe(debug({ title: "tsc" }))
.pipe(...); // <--- if i add notify here,
// I will always get a notification
});
gulp.task("watch", function () {
gulp.watch("ts/**/*.ts", ["scripts:app"]);
});
If I pipe to notify inside the 'scripts:app' task, it will make a notification every time that task runs, regardless of how that task was started. Again, I want to notify when the watched task completes.
I considered adding a task 'scripts:app:notify' that depends on 'scripts:app', but if possible I'd like to avoid creating "unnecessary" tasks.
I also tried the following:
gulp.watch("ts/**/*.ts", ["scripts:app"])
.on("change", function (x) { notify('changed!').write(''); });
But that results in a notification for every file changed. I want a notification when the task completes.
In other words, if I run gulp scripts:app, I should not get a notification. When I run gulp watch and change a watched file, I should get a notification.
How can I do this?
Try adding params to your build script:
function buildApp(notify){
return gulp.src(...)
.pipe(...)
.pipe(function(){
if (notify) {
//drop notification
}
});
});
}
//Register watcher
gulp.watch("ts/**/*.ts", function(){
var notify = true;
buildApp(notify);
});
//Register task so we can still call it manually
gulp.task("scripts:app", buildApp.bind(null, false));
As you can see, buildApp is a simple function. It's callable through a watcher or a "normal" task registration.

Is there a way to synchronously execute multiple JavaScript files in node?

So in Node I can execute a JavaScript file using a command like:
$ node src/someFile.js
But is there a way to execute all of the JavaScript files in a given directory synchronously (one file executes, then after it has finished the next one executes, etc)? Basically, is there a single command that would have the effect of something like
$ node src/firstFile.js
$ node src/secondFile.js
$ node src/thirdFile.js
...
I've tried commands like
$ node src/*.js
but with no success.
If there exists no such command, what's the best way to go about doing something like this?
I am not sure if this is going to work for you because this is a feature of the shell not of the node runtime but..
for f in src/*.js; do node "$f"; done
Or in Powershell:
Get-ChildItem .\*.js | Foreach-Object {
node $_
}
You could use spawn to run a node process from node like
(function() {
var cp = require('child_process');
var childProcess = cp.spawn('node', [`src/firstFile.js`]);
At this point you have to add some listeners:
// now listens events
// Listen for an exit event:
child.on('exit', function(exitCode) {
console.log("Child exited with code: " + exitCode);
return resolve(exitCode);
});
// Listen for stdout data
child.stdout.on('data', function(data) {
console.log(data.toString());
});
// child error
child.stderr.on('data',
function(data) {
console.log('err data: ' + data);
// on error, kill this child
child.kill();
}
);
}).call(this);
Of course you need to serialize execution here, but it's easy since you have the child.on('exit') that tells you that the process ended, so you can start the next one.
Look to Controlling Multiple Processes in Node for my example working solution that run multi processes in node and wait execution to end / join.
Using a POSIX shell:
$ for js in src/*.js; do node "$js"; done
If the calling each one from the shell thing isn't a hard requirement, I would kick them all off with a single node process from the shell. This node script would:
traverse the directory of modules
require the first one, which executes it, and pass a callback which the module will call on completion
When the complete callback is called, execute the next script in your directory.

Execute code in a sandbox, with modules in same context

I'm automating running the ECMA-402 test suite against the Intl polyfill I wrote, and I've hit some problems. Currently, the tests are run against a fully-built version of the library, which means having to recompile every time a change is made before the tests can run. I'm trying to improve it by splitting the code up into separate modules and using require to run the tests.
The main problem comes into focus when I try and run the tests using the vm module. If I add the polyfill to the test's sandbox, some of the tests fail when checking native behaviour — the polyfill's objects don't inherit from the test context's Object.prototype, for example. Passing require to the tests will not work because the modules are still compiled and executed in the parent's context.
The easiest solution in my head was to spawn a new node process and write the code to the process's stdin, but the spawned node process doesn't execute the code written to it and just waits around forever. This is the code I tried:
function runTest(testPath, cb) {
var test,
err = '',
content = 'var IntlPolyfill = require("' + LIB_PATH + '");\n';
content += LIBS.fs.readFileSync(LIBS.path.resolve(TEST_DIR, testPath)).toString();
content += 'runner();';
test = LIBS.spawn(process.execPath, process.execArgv);
test.stdin.write(content, 'utf8');
// cb runs the next test
test.on('exit', cb);
}
Does anyone have any idea why Node.js doesn't execute the code written to its stdin stream, or if there's another way I can get the module to compile in the same context as the tests?
You must close the stdin for the child process to consume data and exit. Do this when you are done passing code.
test.stdin.end();
In the end, I chose to use the -e command line switch to pass the code directly to the new node instance. It only took a slight modification to the code:
function runTest(testPath, cb) {
var test,
err = '',
content = 'var IntlPolyfill = require("' + LIB_PATH + '");\n';
content += LIBS.fs.readFileSync(LIBS.path.resolve(TEST_DIR, testPath)).toString();
content += 'runner();';
test = LIBS.spawn(process.execPath, process.execArgv.concat('-e', content));
// cb runs the next test
test.on('exit', cb);
}

Controlling a specific process id in Node?

I'm developing a node application that allows a client to control a program running on the server. The program must always be running on its own terminal window. Ideal scenario is outlined as follows:
client clicks a button -> command is run in terminal running program-> program does something
I'm not too experienced with node but I know that I can run command line scripts using the ChildProcess event emitter. The issue I'm having is how do I tell node to run a command on a particular process (i.e. the one running the program I'm trying to manipulate). Is there a way to execute commands on a specific process id? Is there a way to detect all current processes and their id's?
Any suggestions or direction would be greatly appreciated.
When you create a child process, you can assign it to a variable so that you can reference it later. In this instance, you may want to add it to an object or array so that you can reference a group of running processes.
You can refer to the documentation for spawn or exec for examples.
One way to send commands to a created child process is using signals, such as child.kill('SIGSOMETHING');
For example:
var spawn = require('child_process').spawn;
function spawnChild() {
var cmd = spawn('cmd', ['-p1', 'param']);
cmd.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});
cmd.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
cmd.on('close', function (code) {
console.log('child process exited with code ' + code);
});
// Save a reference to this child
children.push(cmd);
}
// Spawn 5 children
for (var i = 0; i < 5; i++) {
spawnChild();
}
// Send a signal after 5 seconds
setTimeout(function(){
for (var i in children) {
var child = children[i];
console.log('Sending signal to child with PID: ' + child.pid);
child.kill('SIGSOMETHING');
}
}, 5000);

How to print out a text once grunt task completes?

Once a Grunt task completes, I want to print out some information. See the Grunt snippet below.
Is there a way to achieve this? I noticed that grunt.task.run() does not support callbacks. This causes my message to be printed out prior to coverage report output.
grunt.registerTask('coverage', 'Runs all unit tests available via Mocha and generates code coverage report', function() {
grunt.task.run('env:unitTest', 'mochaTest');
grunt.log.writeln('Code coverage report was generated into "build/coverage.html"');
});
I also want to avoid "hacks" such as creating a grunt task only for printing the information out and adding it to the grunt.task.run() chain of tasks.
Create a task that will run when everything is all done and then add it to your task chain:
grunt.registerTask('alldone', function() {
grunt.log.writeln('Code coverage report was generated into "build/coverage.html"');
});
grunt.registerTask('default', ['env:unitTest', 'mochaTest', 'alldone']);
There is a much better way to do it, without creating an extra task, and modifying anything else.
Grunt is a node process, so you can:
use the process stdout to write what you need
subscribe to the process exit event to do it when a task is finishing its execution
This is a simple example which prints out the time when the tasks has finished their execution:
module.exports = function (grunt) {
// Creates a write function bound to process.stdout:
var write = process.stdout.write.bind(process.stdout);
// Subscribes to the process exit event...
process.on("exit", function () {
// ... to write the information in the process stdout
write('\nFinished at ' + new Date().toLocaleTimeString()+ '\n');
});
// From here, your usual gruntfile configuration, without changes
grunt.initConfig({
When you run any task, you'll see a message at the bottom like:
Finished at 18:26:45

Categories