JavaScript hanging writing errors from a .ps1 script - javascript

Because of reasons, I have a situation in which I need to use a .js file to call a .bat file, which calls a .ps1 file. It may sound crazy, but yes, I have to launch the .ps1 file this way.
My problem is that, the .js file is hanging after writing a variable number of errors. The number of errors that causes the script to hang changes between scripts, but seems to be consistent within a script.
I have included sanitized scripts below.
Every time I run this particular combo using cscript (cscript c:\temp\test.js "c:\temp\test3.bat"), the script stops after writing "Checking device 10 of 100." to the log file and does not return me to the prompt. If I run the .bat file from the same command prompt, the script runs as expected. If, on line 41 of the .ps1 script, I change the message type from "Error" to "Verbose" (for example), the script runs fine and completes as expected.
It seems that the .js file does not like something about "Write-Error $Message" from the Out-PsLogging function but:
I cannot tell what it doesn't like
I cannot tell why it stops writing errors after (in this case) 10 errors
I have seen this behavior on Windows 10 and Server 2019 (ps 5.1).
Code:
test.js
var wshShell = new ActiveXObject("WScript.Shell");
var cmdLine = WScript.Arguments(0);
var result = {};
result.stdout = "";
result.stderr = "";
result.exitCode = -1;
if (!wshShell) {
WScript.Echo("Can not run command");
}
var oExec;
try {
oExec = wshShell.Exec(cmdLine);
WScript.Echo("Ran the command - " + cmdLine);
WScript.Echo(oExec.Status);
var line;
WScript.Echo("About to start while loop");
while (oExec.Status != 1) {
WScript.Echo(oExec.Status);
while (!oExec.StdOut.AtEndOfStream) {
WScript.Echo("Inside the second while loop");
line = oExec.StdOut.ReadLine();
result.stdout += line + "\n";
WScript.Echo(line + "\n");
WScript.Echo(oExec.StdOut.AtEndOfStream);
}
while (!oExec.StdErr.AtEndOfStream) {
WScript.Echo("Inside the third while loop");
line = oExec.StdErr.ReadLine();
result.stderr += line + "\n";
WScript.Echo(line + "\n");
WScript.Echo(oExec.StdErr.AtEndOfStream);
}
WScript.Sleep(100);
}
}
catch (e) {
WScript.Echo("Unable to run command - " + cmdLine);
WScript.Echo(e);
}
test3.bat
cmd.exe /C Powershell.exe -Command "&{C:\temp\test3.ps1 -Verbose}"
test3.ps1
Function Out-PsLogging {
[CmdletBinding(DefaultParameterSetName = 'SessionOnly')]
param(
[Parameter(Mandatory, ParameterSetName = 'File')]
[System.IO.FileInfo]$LogPath,
[Parameter(Mandatory)]
[string]$Message,
[Parameter(Mandatory)]
[ValidateSet('Info', 'Warning', 'Error', 'Verbose', 'First')]
[string]$MessageType
)
$logType = "LogFile"
Switch ($logType) {
"LogFile" {
Switch ($MessageType) {
"Info" { [System.IO.File]::AppendAllLines([string]$LogPath, [string[]]$Message); Write-Host $Message }
"Warning" { [System.IO.File]::AppendAllLines([string]$LogPath, [string[]]$Message); Write-Warning $Message }
"Error" { [System.IO.File]::AppendAllLines([string]$LogPath, [string[]]$Message); Write-Error $Message }
"Verbose" { [System.IO.File]::AppendAllLines([string]$LogPath, [string[]]$Message); Write-Verbose $Message -Verbose }
"First" { [System.IO.File]::WriteAllLines($LogPath, $Message); Write-Verbose $Message -Verbose }
}
}
}
}
$a = 0
$array = #(1..100)
$LogPath = 'C:\temp\log3.txt'
$message = ("{0}: Beginning {1}." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $myinvocation.MyCommand)
Out-PsLogging -LogPath $LogPath -MessageType First -Message $message
$itGlueConfigsMatchingPolicy = Foreach ($device in $array) {
$a++
$message = ("{0}: Checking device {1} of {2}." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $a, $array.count)
Out-PsLogging -LogPath $LogPath -MessageType Error -Message $message
}; Remove-Variable a -Force
$message = ("{0}: Completed {1}." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $myinvocation.MyCommand)
Out-PsLogging -LogPath $LogPath -MessageType Verbose -Message $message

Turns out the issue is a bug in wscript: https://groups.google.com/forum/#!topic/microsoft.public.scripting.wsh/kIvQsqxSkSk

Related

Creating a bat file to download a program and I can't find the issue

Says the url is wrong but it seems right to me.
I'm trying to download a file from the internet launch the program, then after the process ends to delete the program.
Any help would be great
process will be
start exe ---> to create the simple downloader ---> add parameters via bat file ---> launch the file -----> wait for the process to end -----> delete the files downloaded.
I have yet to add the wait process and delete commands
#if (#X)==(#Y) #end /****** jscript comment ******
#echo off
::::::::::::::::::::::::::::::::::::
::: compile the script ::::
::::::::::::::::::::::::::::::::::::
setlocal
if exist simpledownloader.exe goto :skip_compilation
set "frm=%SystemRoot%\Microsoft.NET\Framework\"
:: searching the latest installed .net framework
for /f "tokens=* delims=" %%v in ('dir /b /s /a:d /o:-n "%SystemRoot%\Microsoft.NET\Framework\v*"') do (
if exist "%%v\jsc.exe" (
rem :: the javascript.net compiler
set "jsc=%%~dpsnfxv\jsc.exe"
goto :break_loop
)
)
echo jsc.exe not found && exit /b 0
:break_loop
call %jsc% /nologo /out:"simpledownloader.exe" "%~dpsfnx0"
::::::::::::::::::::::::::::::::::::
::: end of compilation ::::
::::::::::::::::::::::::::::::::::::
:skip_compilation
:: download the file
::
::::::::::
:: simpledownloader.exe "%%~1" "%%~2"
simpledownloader.exe "https://download.splashtop.com/sos/SplashtopSOS.exe" sos.exe
sos.exe
:: del /q simpledownloader.exe
::
::::::::
::
exit /b 0
****** end of jscript comment ******/
import System;
var arguments:String[] = Environment.GetCommandLineArgs();
var webClient:System.Net.WebClient = new System.Net.WebClient();
print("Downloading " + arguments[1] + " to " + arguments[2]);
try {
webClient.DownloadFile(arguments[1], arguments[2]);
} catch (e) {
Console.BackgroundColor = ConsoleColor.Green;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n\nProblem with downloading " + arguments[1] + " to " + arguments[2] + "Check if the internet address is valid");
Console.ResetColor();
Environment.Exit(5);
}
I think I found something for you I made some adjustments for you.
Happy scripting!
#echo off
IF EXIST sos.exe goto delete
IF NOT EXIST sos.exe goto skip
:delete
echo delete
del /f sos.exe
timeout 5
:skip
echo skip
rem :: the first argument is the script name as it will be used for proper help message
cscript //E:JScript //nologo "%~f0" "%~nx0" %*
start sos.exe
exit /b %errorlevel%
#if (#X)==(#Y) #end JScript comment */
// global variables and constants
var ARGS = WScript.Arguments;
var scriptName=ARGS.Item(0);
var url="";
var saveTo="";
var user=0;
var pass=0;
var proxy=0;
var bypass="";
var proxy_user=0;
var proxy_pass=0;
var certificate=0;
var force=true;
//ActiveX objects
//Use the right version of MSXML
/*var progIDs = [ 'Msxml2.DOMDocument.6.0', 'Msxml2.DOMDocument.5.0', 'Msxml2.DOMDocument.4.0', 'Msxml2.DOMDocument.3.0', 'Msxml2.DOMDocument' ]
for (var i = 0; i < progIDs.length; i++) {
try {
var XMLHTTPObj = new ActiveXObject(progIDs[i]);
}catch (ex) {
}
}
if typeof XMLHTTPObj === 'undefined'{
WScript.Echo ("You are using too ancient windows or you have no installed IE");
WScript.Quit(1);
}*/
var XMLHTTPObj = new ActiveXObject("MSXML2.XMLHTTP");
var FileSystemObj = new ActiveXObject("Scripting.FileSystemObject");
var AdoDBObj = new ActiveXObject("ADODB.Stream");
function existsItem(path){
return FileSystemObj.FolderExists(path)||FileSystemObj.FileExists(path);
}
stripTrailingSlash = function(path){
while (path.substr(path.length - 1,path.length) == '\\') {
path=path.substr(0, path.length - 1);
}
return path;
}
function deleteItem(path){
if (FileSystemObj.FileExists(path)){
FileSystemObj.DeleteFile(path);
return true;
} else if (FileSystemObj.FolderExists(path) ) {
FileSystemObj.DeleteFolder(stripTrailingSlash(path));
return true;
} else {
return false;
}
}
function writeFile(fileName,data ){
AdoDBObj.Type = 1;
AdoDBObj.Open();
AdoDBObj.Position=0;
AdoDBObj.Write(data);
AdoDBObj.SaveToFile(fileName,2);
AdoDBObj.Close();
}
function download( url,file){
if (force && existsItem(file)){
if(!deleteItem(file)){
WScript.Echo("Unable to delete "+ file);
WScript.Quit(8);
}
}else if (existsItem(file)){
WScript.Echo("Item " + file + " already exist");
WScript.Quit(9);
}
if (proxy!=0 && bypass !="") {
//https://msdn.microsoft.com/en-us/library/ms760236(v=vs.85).aspx
XMLHTTPObj.setProxy(SXH_PROXY_SET_DIRECT,proxy,bypass);
} else if (proxy!=0) {
XMLHTTPObj.setProxy(SXH_PROXY_SET_DIRECT,proxy,"");
}
if (proxy_user!=0 && proxy_pass!=0 ) {
//https://msdn.microsoft.com/en-us/library/ms763680(v=vs.85).aspx
XMLHTTPObj.setProxyCredentials(proxy_user,proxy_pass);
}
if(certificate!=0) {
//https://msdn.microsoft.com/en-us/library/ms763811(v=vs.85).aspx
WinHTTPObj.setOption(3,certificate);
}
if (user!=0 && pass!=0){
//https://msdn.microsoft.com/en-us/library/ms757849(v=vs.85).aspx
XMLHTTPObj.Open('GET',url,false,user,pass);
} else {
XMLHTTPObj.Open('GET',url,false);
}
XMLHTTPObj.Send();
var status=XMLHTTPObj.Status;
switch(status){
case 200:
WScript.Echo("Status: 200 OK");
break;
case 401:
WScript.Echo("Status: 401 Unauthorized");
WScript.Echo("Check if correct user and password were provided");
WScript.Quit(401);
break;
case 407:
WScript.Echo("Status:407 Proxy Authentication Required");
WScript.Echo("Check if correct proxy user and password were provided");
WScript.Quit(407);
break;
default:
WScript.Echo("Status: "+status);
WScript.Echo("Try to help yourself -> https://en.wikipedia.org/wiki/List_of_HTTP_status_codes");
WScript.Quit(status);
}
writeFile(file,XMLHTTPObj.ResponseBody);
}
function main(){
url="https://download.splashtop.com/sos/SplashtopSOS.exe"
saveTo="sos.exe";
download(url,saveTo);
}

Live iPerf Output Printed to HTML with PHP/Ajax

I've been working on a web interface for iPerf and it's going pretty well. My goal is to have the output of the commands be streamed live on the page. It works for iPerf2 commands but when I run iPerf3, it only shows the output once the entire test is complete.
Based on my research I've done on this site and others, I'm thinking it might have something to do with the buffer. I've been messing around with flushing the buffer at different times or setting the 'fread' length to different values but I can't get it to act the same as regular iperf commands. I think this because instead of running the 'popen' on the iperf command itself, I used popen on a python script that would run the iperf command. This still returned the same issue. It only shows the output on the web page once the entire test is complete.
Here is my code:
phpQ.php
<!DOCTYPE html>
<html>
<body>
<div>
Server Domain/IP Address: <input id="address" type="text"><br>
<input id="run" type="button" value="iPerf"><br><br>
</div>
<div id="result"></div>
<script>
function updateText(address) {
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (this.readyState == 3) {
var old_value = document.getElementById("result").innerHTML;
document.getElementById("result").innerHTML = this.responseText;
}
};
if (purpose == 1) {
var url = 'ajaxQ.php?address='+address;
ajax.open('GET', url,true);
ajax.send();
}
}
document.getElementById("run").onclick = function(){
address = document.getElementById("address").value;
purpose = 1;
updateText(address);
}
</script>
</body>
</html>
ajaxQ.php - to see the difference, change "iperf -c" to "iperf3 -c" in the $iperfCmd variable.
<?php
function liveExecuteCommand($cmd,$address)
{
while (# ob_end_flush()); // end all output buffers if any
// tells the user what command is going to run
echo "<pre>Running Command: '".$cmd."'</pre>";
// open the command to run and read output
$proc = popen("$cmd", 'r');
$live_output = "";
$complete_output = "";
while (!feof($proc))
{
# flush();
$live_output = fread($proc,4096);
// adds the live output to the complete output
$complete_output = $complete_output . $live_output;
// prints the live output
echo "<pre>$live_output</pre>";
}
sleep(1);
// close the process
pclose($proc);
echo "<pre>------------------------------------------------------------\nAll Done!</pre>";
}
// this happens if the iPerf button is pressed
if (isset($_GET['address'])) {
$address = $_GET['address'];
$iperfCmd = "iperf -c ".$address." -i 1 -t 5";
liveExecuteCommand($iperfCmd,$address);
}
else{
echo "No post request";
}
?>
FYI, I am running the iperf client on an 'Ubuntu 16.04.2 LTS' CLI server and the iperf server on an 'Ubuntu 16.04 LTS' desktop server.
Thanks for any help!

I want to clear contents of file in chrome extension and the file is on server. How to do that?

I have written the below code in my js file in chrome extension.
var xhr_put = new XMLHttpRequest();
xhr_put.open('PUT',"https://something/index.php",true);
xhr_put.onreadystatechange = function()
{
console.log('File Cleared',"Yes");
}
And the below code in my PHP file.
$requestmethod = 'PUT';
if ($_REQUEST['REQUEST_METHOD'] === $requestmethod)
{
$f = #fopen("facebookmsg.txt", "w");
print "in here";
if ($f !== false) {
ftruncate($f, 0);
fclose($f);
echo "here";
}
}
But my file on server is not getting empty. I need help as to what is wrong and how do i correct it?

JS not working properly in firefox

I am using qzprint API for printing labels in my open cart extension. Everything was working fine but suddenly it stopped working on FF. In Internet explorer it works fine. If i add alerts in my functions of applet it works fine on firefox as well but not sure why not with out alerts. here is my code.
calling applet functions in my header.tpl
<script type="text/javascript">
deployQZ('<?php echo HTTP_CATALOG ?>');
useDefaultPrinter();
<script>
Applet file containing functions
function deployQZ(path) {
//alert("alert for printing label");
pathApplet = path + 'java/qz-print.jar';
pathJnlp = path + 'java/qz-print_jnlp.jnlp';
var attributes = {id: "qz", code:'qz.PrintApplet.class',
archive: pathApplet, width:1, height:1};
var parameters = {jnlp_href: pathJnlp,
cache_option:'plugin', disable_logging:'false',
initial_focus:'false'};
if (deployJava.versionCheck("1.7+") == true) {}
else if (deployJava.versionCheck("1.6+") == true) {
attributes['archive'] = 'java/jre6/qz-print.jar';
parameters['jnlp_href'] = 'java/jre6/qz-print_jnlp.jnlp';
}
deployJava.runApplet(attributes, parameters, '1.5');
}
/**
* Automatically gets called when applet has loaded.
*/
function qzReady() {
// Setup our global qz object
window["qz"] = document.getElementById('qz');
//var title = document.getElementById("title");
if (qz) {
try {
//title.innerHTML = title.innerHTML + " " + qz.getVersion();
//document.getElementById("content").style.background = "#F0F0F0";
} catch(err) { // LiveConnect error, display a detailed meesage
document.getElementById("content").style.background = "#F5A9A9";
alert("ERROR: \nThe applet did not load correctly. Communication to the " +
"applet has failed, likely caused by Java Security Settings. \n\n" +
"CAUSE: \nJava 7 update 25 and higher block LiveConnect calls " +
"once Oracle has marked that version as outdated, which " +
"is likely the cause. \n\nSOLUTION: \n 1. Update Java to the latest " +
"Java version \n (or)\n 2. Lower the security " +
"settings from the Java Control Panel.");
}
}
}
/**
* Returns is the applet is not loaded properly
*/
function isLoaded() {
if (!qz) {
alert('Error:\n\n\tPrint plugin is NOT loaded!');
return false;
} else {
try {
if (!qz.isActive()) {
alert('Error:\n\n\tPrint plugin is loaded but NOT active!');
return false;
}
} catch (err) {
alert('Error:\n\n\tPrint plugin is NOT loaded properly!');
return false;
}
}
return true;
}
function useDefaultPrinter() {
//alert("alert for printing label");
if (isLoaded()) {
// Searches for default printer
qz.findPrinter();
// Automatically gets called when "qz.findPrinter()" is finished.
window['qzDoneFinding'] = function() {
// Alert the printer name to user
var printer = qz.getPrinter();
//alert(printer !== null ? 'Default printer found: "' + printer + '"':
//'Default printer ' + 'not found');
document.getElementById("name_printer").innerHTML = 'Default printer found: "' + printer + '"';
// Remove reference to this function
window['qzDoneFinding'] = null;
defaultFound = true;
};
}
}
As u can see in my deployqz() and usedefaultprinter() functions i have alert on first line which is in comments if its commented it doesn't work in fire fox and if not commented than it works fine. With comments i get alert message from isLoaded() function "Print plugin is NOT loaded properly!".
Also in my console i get this
An unbalanced tree was written using document.write() causing data from the network to be reparsed. For more information https://developer.mozilla.org/en/Optimizing_Your_Pages_for_Speculative_Parsing
Try this:
If the qzReady is called by the applet when ready, put useDefaultPrinter inside that function.
if isLoaded takes some time, call useDefaultPrinter in there too using setTimeout
Like this
<script type="text/javascript">
deployQZ('<?php echo HTTP_CATALOG ?>');
<script>
Applet file containing functions
var qz;
function deployQZ(path) {
pathApplet = path + 'java/qz-print.jar';
pathJnlp = path + 'java/qz-print_jnlp.jnlp';
var attributes = {id: "qz", code:'qz.PrintApplet.class',
archive: pathApplet, width:1, height:1};
var parameters = {jnlp_href: pathJnlp,
cache_option:'plugin', disable_logging:'false',
initial_focus:'false'};
if (deployJava.versionCheck("1.7+") == true) {}
else if (deployJava.versionCheck("1.6+") == true) {
attributes['archive'] = 'java/jre6/qz-print.jar';
parameters['jnlp_href'] = 'java/jre6/qz-print_jnlp.jnlp';
}
deployJava.runApplet(attributes, parameters, '1.5');
}
/**
* Automatically gets called when applet has loaded.
*/
function qzReady() {
// Setup our global qz object
qz = document.getElementById('qz');
if (qz) {
try {
useDefaultPrinter();
} catch(err) { // LiveConnect error, display a detailed meesage
document.getElementById("content").style.background = "#F5A9A9";
alert("ERROR: \nThe applet did not load correctly. Communication to the " +
"applet has failed, likely caused by Java Security Settings. \n\n" +
"CAUSE: \nJava 7 update 25 and higher block LiveConnect calls " +
"once Oracle has marked that version as outdated, which " +
"is likely the cause. \n\nSOLUTION: \n 1. Update Java to the latest " +
"Java version \n (or)\n 2. Lower the security " +
"settings from the Java Control Panel.");
}
}
else { setTimeout(useDefaultPrinter,300); }
}
/**
* Returns is the applet is not loaded properly
*/
function isLoaded() {
if (!qz) {
alert('Error:\n\n\tPrint plugin is NOT loaded!');
return false;
} else {
try {
if (!qz.isActive()) {
alert('Error:\n\n\tPrint plugin is loaded but NOT active!');
return false;
}
} catch (err) {
alert('Error:\n\n\tPrint plugin is NOT loaded properly!');
return false;
}
}
return true;
}
function useDefaultPrinter() {
//alert("alert for printing label");
if (isLoaded()) {
// Searches for default printer
qz.findPrinter();
// Automatically gets called when "qz.findPrinter()" is finished.
window['qzDoneFinding'] = function() {
// Alert the printer name to user
var printer = qz.getPrinter();
//alert(printer !== null ? 'Default printer found: "' + printer + '"':
//'Default printer ' + 'not found');
document.getElementById("name_printer").innerHTML = 'Default printer found: "' + printer + '"';
// Remove reference to this function
window['qzDoneFinding'] = null;
defaultFound = true;
};
}
else { setTimeout(useDefaultPrinter,300); }
}

PhantomJS hanging when called from CLI or Web

I'm trying to use phantomJS to capture a screenshot of a URL, however when I call phantomJS (from either the command line or web app) it hangs and seesm to never execute the "exit()" call. I can't seem to find any error messages and it remains running until I kill it. This is the JS file that is passed to the phantomjs command:
var page = require('webpage').create();
var system = require('system');
var script_address = '';
var page_to_load = '';
var members_id = '';
var activities_id = '';
var folder_path = '';
if (system.args.length < 5)
{
console.log('Usage: phantom_activity_fax.js script_address page_to_load members_id activities_id folder_path');
console.log('#Args: '+system.args.length);
phantom.exit();
}//END IF SYSTEM.ARGS.LENGTH === 1
//ASSIGN OUR ARGUMENTS RECIEVED
script_address = system.args[0];
page_to_load = system.args[1];
members_id = system.args[2];
activities_id = system.args[3];
folder_path = system.args[4];
console.log(system.args[0]);
console.log(system.args[1]);
console.log(system.args[2]);
console.log(system.args[3]);
console.log(system.args[4]);
//OPEN OUR PAGE WITH THE VALUES PROVIDED
page.open(page_to_load, function () {
console.log("Entering Anonymous Function, Beginning RENDER:\n");
page.render(folder_path+members_id+'_'+activities_id+'.png');
phantom.exit();
});
I see the values pushed to the console, but after that it just hangs :( I've tried the web inspector, but could not understand where to execute the __run() call, and didn't see any change when I added the debugger-autorun=yes to the call :(.
This is the output I get from the command line when it hangs (as root user):
[root#wv-wellvibe2 faxes]# phantomjs /var/www/wv-wellvibe2-test/javascripts/phantom_activity_fax.js https://wv-wellvibe2-test/manual_scripts/phantom_js_test_page.php 397 0 /var/www/wv-wellvibe2-test/uploads/images/faxes/
/var/www/wv-wellvibe2-test/javascripts/phantom_activity_fax.js
https://wv-wellvibe2-test/manual_scripts/phantom_js_test_page.php
397
0
/var/www/wv-wellvibe2-test/uploads/images/faxes/
And this is the output I get when running it as my own user, but I don't see the image file in the designated folder (faxes):
[user#wv-wellvibe2 ~]$ phantomjs /var/www/wv-wellvibe2-test/javascripts/phantom_activity_fax.js https://wv-wellvibe2-test/manual_scripts/phantom_js_test_page.php 397 0 /var/www/wv-wellvibe2-test/uploads/images/faxes/
/var/www/wv-wellvibe2-test/javascripts/phantom_activity_fax.js
https://wv-wellvibe2-test/manual_scripts/phantom_js_test_page.php
397
0
/var/www/wv-wellvibe2-test/uploads/images/faxes/
Entering Anonymous Function, Beginning RENDER:
[user#wv-wellvibe2 ~]$
Unfortunately, as I said, the command completed but did not save a .png in the faxes folder. Here is the permissions for that folder:
[root#wv-wellvibe2 faxes]# ls -la
total 12
drwxr-xr-x 3 root apache 4096 May 16 15:31 .
drwxr-xr-x 5 apache apache 4096 May 16 14:14 ..
drwxr-xr-x 6 apache apache 4096 May 20 15:05 .svn
Please let me know if there is anything else I can provide!
Thank you!
(As requested here is the PHP script that calls the Phantom JS process)
header("Date: " . date('Y-m-d H:i:s'));
//GET THE SMARTY CONFIG
include_once $_SERVER['DOCUMENT_ROOT'] . "/smarty/configs/config.php";
//VARS USED LATER
$process_script = $_SERVER['DOCUMENT_ROOT'] . '/javascripts/phantom_activity_fax.js';
$page_to_load = 'https://' . $_SERVER['HTTP_HOST'] . '/manual_scripts/phantom_js_test_page.php';
$members_id = $_SESSION['members_id'];
$activities_id = 0;
$folder_path = $_SERVER['DOCUMENT_ROOT'] . 'uploads/images/faxes/';
$system_response = '';
$call = "phantomjs --remote-debugger-port=65534 --remote-debugger-autorun=yes " . $process_script . " " . $page_to_load . " " . $members_id . " " . $activities_id . " " . $folder_path;
echo 'CallingSystemWith: ' . $call . '<br />';
try
{
$system_response = system($call);
echo '<br />SystemResponse: ' . $system_response . '<hr />';
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}//END TRY / CATCH
(The page it tells PhantomJS to "scrape" is a simple PHP script that outtputs a print_r() of $_SESSION and $_REQUEST)
If something goes wrong in your script (such as in page.render), phantom.exit() will never be called. That's why phantomJs seems to hang.
Maybe there is an issue in page.render but I don't think so. The most common causes of hangs are unhandled exception.
I will suggest you 4 things to investigate the issue :
add an handler to phantom.onError and/or to page.onError
encapsulate your code in try/catch blocks (such as for page.render)
Once the page is loaded, there is no test on callback status. It's better to check the status
seems to freeze when calling page.render. Have you tried a simpler filename in the current directory ? Maybe the freeze is because of the security or invalid filename (invalid characters ?)
Hope this will help you
Use :
$phantomjs --debug=true rasterize.js http://... test.pdf
In rasterize.js add a timeout on ressource, that was my problem:
page.settings.resourceTimeout = 10000; // Avoid freeze!!!

Categories

Resources