albciff
albciff

Reputation: 18517

How to use child process module on windows from PhantomJS/CasperJS

I'm using CasperJS to test my webApp, the thing is that I need to access a DB to automatize some necessary inputs from my tests.

I'm looking for an alternatives on how to retrieve this data from the DB inside a casperJS js script an finally I decide to use phantomJS child process module to call a groovy script to connect a DB and make a select and print the result to stdout to get it from CasperJS. However from the sample of the phantomJS can not realize how to do it, based on the sample I made some attempts with spawn and execFile with no luck. i.e I try:

var process = require("child_process")
var spawn = process.spawn
var execFile = process.execFile

var child = spawn("groovy", ["script.groovy"])

child.stdout.on("data", function (data) {
  console.log("spawnSTDOUT:", JSON.stringify(data))
})

child.stderr.on("data", function (data) {
  console.log("spawnSTDERR:", JSON.stringify(data))
})

child.on("exit", function (code) {
  console.log("spawnEXIT:", code)
})

This doesn't work and not produce any output. I also try directly executing dir command directly and also nothing happens.

I try also with linux and it doesn't work either, I try also creating a simple echo .sh and nothing..., however in linux when I try to run ls command this times it works as expected.

Upvotes: 1

Views: 739

Answers (1)

albciff
albciff

Reputation: 18517

After some tries I found a way to do it.

Seems that in windows the only way to do it is passing cmd.exe as command and groovy script.groovy as argument.

So I use

var child = spawn("cmd.exe", ["/k","groovy script.groovy"])

instead of:

var child = spawn("groovy", ["script.groovy"])

This way works correctly on windows.

I also found the way to run a shell script on linux, which executes the groovy.It's similar to the windows solution, instead of invoke .sh I've to use sh command:

var child = spawn("sh", ["script.sh"])

And script.sh executes the groovy script:

#!/bin/bash
groovy script.groovy

Upvotes: 2

Related Questions