POST call from phantomJS doesn't hit server running from grunt - javascript

Here is my setup.
I have a grunt task that does 2 things: 1) start a http server listening on some port 2) triggers another grunt task
The grunt task triggered above is a testem task that runs tests on test-index.html page in PhantomJS.
The test-index.html page sends a POST call on the port on which I start a server in the first grunt task.
Issue: The POST call doesn't hit my server.
Note: If I run the same server manually (not from grunt) and then run the test grunt task, the POST call hits the server.
Heres the code:
Grunt task
grunt.registerMultiTask('coverage', 'Generates coverage reports for JS using Istanbul', function () {
var server = http.createServer(function(req, resp) {
resp.setHeader("Access-Control-Allow-Origin", "*");
console.log('Got something');
req.pipe(fs.createWriteStream('coverage.json'))
resp.end();
});
var port = 7358;
server.listen(port);
// This task simply executes a command: `testem.js ci`
grunt.task.run('testem').then(function() {
server.close();
});
});
test-index.html (somewhere in the )
function onTestemLoad() {
Testem.on('all-test-results', function(results){
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:7358/');
xhr.send(JSON.stringify(window.__coverage__))
});
}
Can anyone point what might be going wrong here?

you've been misled by grunt.task.run!
This line does NOT run the task, it just puts it on the top of the list of tasks to run once the current task is done (http://gruntjs.com/api/grunt.task#grunt.task.run).
A second issue is that when a task completes, it takes down all its running processes with it.
So what happens is:
coverage starts, spins on your server, then register testem as next task
coverage ends, taking down your server
next task (= testem) runs, but no server is here to answer...
You can fix it by doing the following 2 things:
inline your test: replace grunt.task.run('testem') with a direct call to testem
ensure your tests run synchronously - or keep your task alive until your tests are done (using this.async - see http://gruntjs.com/api/inside-tasks#this.async).

Related

JavaScript file can't work while the code work with node in Terminal

I start a java client listening on localhost:8887
And I try this
var net = require('net')
var coon = net.connect(8887,'127.0.0.1')
coon.write('hi')
coon.destroy()
in Terminal with node. The client get the message.
Then I write it into a file test.js and use 'node test.js' in the Terminal, but the client can't get the message. How can I solve this problem.
I add
console.log(coon.remoteAddress+':'+coon.remotePort)
in the code. When I run 'node test.js', it shows that 'undefined:undefined'
Chances are you type into the terminal slow enough for the connection to be made. When you run the whole script, you're attempting to write before there is a connection.
Use the 3rd connectionListener argument
const coon = net.connect(8887, 'localhost', () => {
coon.write('hi');
coon.destroy();
});
See https://nodejs.org/api/net.html#net_net_connect_port_host_connectlistener

HTTP Server stops after some time (Node.js)

INFO: I'm referring to this question I asked on Super User, but couldn't get an answer and I think this is a good place to ask, since the problem is probably code related.
I'm currently running a simple Node.JS server with express.js on my RaspberryPi with Debian installed on it. Everything works fine, but every morning I wake up to see my server isn't running anymore (the server process I started with the command node main.js).
My first guess was, that the Pi has some kind of sleep mode, which it enters after a couple of hours without traffic/etc, and which shuts down the server, but I also run a dydns-client, which is still up every morning (I also was informed, that the RaspberryPi doesn't come with a sleep mode).
I wrote a simple script to check whether the process is running and writes it into a log file, but today morning I had to notice, that this script was wasn't running as well (only for around two hours, it logs the server state every 15 seconds and the last state was running).
Here is the script:
#!/bin/sh
MATCH="SOME_PROCESS_NAME"
while [ true ]
do
if [ "$(ps -ef | grep ${MATCH} | grep -v grep)" ]; then
echo "$(date): Process is running ..."
else
echo "$(date): Process has ended ..."
fi
sleep 15
done
Is there a way to track a process after I started it to check tomorrow morning, what killed my process or why it ended (the script obviously didn't work)?
The server itself looks pretty simple and I don't think there is some kind of auto-shutdown I missed. Here is the code I used.
var express = require('express');
var path = require('path');
var server = express();
server.use(express.static(path.join(__dirname, 'public')));
server.listen(1337);
console.log("Server listening (PORT: " + 1337 + ") ...");
Any idea what to do, to keep the server running/find out what is the stopping reason?
UPDATE: I received a working answer over at RaspberryPi-stackexchange.
My guess is the Raspberry Pi restarts at midnight or something similar. to fix this maybe add an entry for your server process rc.local file. you can add commands to the rc.local file by editing /etc/rc.local
Would this helps https://raspberrypi.stackexchange.com/questions/8741/when-does-the-os-kill-an-application ?
I would like to suggest a different approach to monitor your process until you can get more information, to edit, then check, then start (wrote on the fly)
var fs = require('fs')
var spawn = require('child_process');
var child = spawn(process.argv[0], 'your/bin.js', {stdio:['ignore', 'pipe', 'pipe']})
child.stdout.pipe(fs.createReadStream('stdout.log'))
child.stderr.pipe(fs.createReadStream('stderr.log'))
child.on('error', function (err) {
fs.writeFile('error.log', JSON.stringify(err), function () { /* void */ })
})
child.on('close', function (code, signal) {
fs.writeFile('exit.log', "code="+code+" signal="+signal, function () { /* void */ })
})

Grunt start Node Server and then open browser

I have grunt task that starts the server:
module.exports = function(grunt){
grunt.registerMultiTask('connect', 'Run a simple Node Server', function(){
var options = this.options();
// Tell Grunt this task is asynchronous.
var done = this.async();
var server = connect();
server.use(function(request, response, nxt){
...
});
server.listen(port);
});
};
Now I want to use grunt to start this node server first and then open the browser using grunt-open plugin.
grunt.task.run(['startServer', 'open']);
But startServer task in blocking the open task as the server keeps on listening. What should I do to keep this node server running and open the browser once the server starts?
I had the same problem as yours and I worked in Windows environment. My solution was to put the web server codes in a file for example myServer.js, and use cmd: "start node \"path\to\myServer.js" within the grunt-exec settings.
Example:
Let's assume my server file is located on the following path: D:\SourceCodes\WebServer\myServer.js
ip address and port of my server is 192.168.1.1:8080,
and my webpage is index.html
Then the Gruntfile.js would be:
module.exports = function (grunt) {
grunt.initConfig({
exec: {
run_server:{
cwd: "D:/SourceCodes/WebServer/",
cmd: "start node \"D:/SourceCodes/WebServer/myServer.js\""
},
open_web:{
cmd: "start chrome http://192.168.1.1:8080/index.html"
}
});
grunt.loadNpmTasks('grunt-exec');
grunt.registerTask('default', ['exec']);
}
Two things:
your 'connect' task currently blocks while waiting, you have to tell it to let the grunt process run asynchronously: call done() at the end
...
server.listen(port);
done();
});
now your build will end at the end of your task list, and take down your server with it. So you have to add a task to keep it alive. I suggest using grunt-contrib-watch, but you may choose any one you like, as long as it's a blocking task:
grunt.task.run(['startServer', 'open', 'watch]);
By the way, why are you calling grunt.task.run instead of defining your own task sequence grunt.registerTask('default', ['startServer', 'open', 'watch]); ?

Grunt task - wait for server (selendroid) to be ready

I want to wait for a server to be ready, then run a task on top of it
EDIT:
I've got some of this figured out. I am properly filtering for my string. However, how can I keep this running in the background, and have it terminate when a grunt sequence is complete?
Consider
grunt common server spec-e2e
This will run the common tasks, run the grunt server, then (without stopping the server) runs the next task on top. After all of this is complete, it turns off the server automatically.
That's the kind of functionality that I'm trying to create.
A couple important points that I learned:
Processes started from node - e.g. require('child_process').spawn(...) - will continue to run for all subsequent grunt tasks (they won't be closed once the single task completes).
Once grunt is finished running the sequence of tasks, it will terminate all spawned processes.
Therefore, the command grunt selendroid:selendroid.jar spec-e2e - where the selendroid task starts a server - will keep the server running until after the spec-e2e task completes.
The code for my selendroid task is:
grunt.registerTask('selendroid', 'Start selendroid server', function (appLocation) {
var done = this.async();
var timeout = setTimeout(function() {
console.log('Selendroid took too long to start');
done(false);
}, 30000);
function checkLoaded(data) {
data = data.toString();
if (data.indexOf('Selendroid standalone server has been started on port') > -1) {
clearTimeout(timeout);
done();
}
}
if (typeof appLocation === 'undefined') {
console.log('App to test not set, aborting...'.red);
done(false);
}
var cmd = require('child_process').spawn('java', ['-jar', 'selendroid.jar', '-app', appLocation]);
cmd.stdout.on('data', function(data) {
checkLoaded(data);
});
cmd.stderr.on('data', function(data) {
checkLoaded(data);
});
});

Restart a node.js app from code level

I've an app which initially creates static config files (once) and after files were written I need to reinitialize/restart the application.
Is there something to restart a node.js app from itself?
This is required cause I've an application running in two runlevels in node.js.
The initial one starts completly synchronus and after this level has been completed app is in async runlevel in a previously started environment.
I know there are tools like nodemon but that's not what I need in my case.
I tried to kill the app via process.kill() which is working but I can't listen to the kill event:
// Add the listener
process.on('exit', function(code) {
console.log('About to exit with code:', code);
// Start app again but how?
});
// Kill application
process.kill();
Or is there a better, cleaner way to handle this?
Found a working case to get node.js restarted from app itself:
Example:
// Optional part (if there's an running webserver which blocks a port required for next startup
try {
APP.webserver.close(); // Express.js instance
APP.logger("Webserver was halted", 'success');
} catch (e) {
APP.logger("Cant't stop webserver:", 'error'); // No server started
APP.logger(e, 'error');
}
// First I create an exec command which is executed before current process is killed
var cmd = "node " + APP.config.settings.ROOT_DIR + 'app.js';
// Then I look if there's already something ele killing the process
if (APP.killed === undefined) {
APP.killed = true;
// Then I excute the command and kill the app if starting was successful
var exec = require('child_process').exec;
exec(cmd, function () {
APP.logger('APPLICATION RESTARTED', 'success');
process.kill();
});
}
The only con I can see here is to loose outputs on console but if anything is logged into logfiles it's not a problem.

Categories

Resources