Plupload retry if error - javascript

I'm trying to setup plupload so that if a file upload fails according to a certain error code, plupload will try to upload it again. Without success.
What I currently have
Here is my piece of code for now :
var attempts = 0; // number of attempts
function init(uploader) {
uploader.bind('Error', function(up, file) {
var code = JSON.parse(file.response).error.code;
console.log(code); //logs the error code
if(code === 503 && attempts > 3) {
up.stop();
file.status = plupload.FAILED;
file.retry = false;
// do stuff...
up.state = plupload.STARTED;
up.trigger("StateChanged");
attempts = 0;
}
else {
console.log("attempt : "+ attempts);
up.stop();
file.status = plupload.QUEUED;
attempts++;
file.retry = true;
up.state = plupload.STARTED;
up.trigger("StateChanged");
up.trigger("QueueChanged"); // ERROR HERE
}
})
}
Where I indicated the "ERROR HERE", my console shows me this :
TypeError: n.getSource is not a function
What am I doing wrong ?
Thanks a lot !

Why don't you add the file again on the queue?
http://www.plupload.com/docs/Uploader#addFile-filefileName-method
addFile(file, [fileName])

Related

my functions are mixed and the engine executing what ever he wants

so i was told to Present a loader to the user when a call is made to the server (indicating the server is calculating) Present an error to the user if the input number is more than 50, and do not send a server request Try passing the number 42 to the server. The server will send back an error, present this error to the user.
now what i did is everything besides the last error to present it to the user.
i have tried everything i could think of, and no matter what the user types, it displays both of the messages.
this is my code:
const clcBtn = document.getElementById("calcButton");
let clcInput = document.getElementById("calcInput");
const result = document.getElementById('paragraph');
const loader = document.getElementById('spinner');
const error = document.getElementById('error-message');
const serverError = document.getElementById('server-error');
clcBtn.addEventListener("click", calcFunc);
function numValidate(value) {
if(value > 50) {
return false;
}
return true;
}
function calcFunc() {
if (!numValidate (clcInput.value)) {
error.style.display = "block"
setTimeout(() => {
error.style.display = "none";
}, 5000);
console.error("Can't be larger than 50") // only bec it's a cool feature :D
return;
}
loader.classList.add("spinner-border");
fetch(`http://localhost:5050/fibonacci/${clcInput.value}`).then(function (response) {
return response.json().then(function (data) {
result.innerHTML = data.result;
});
});
setTimeout(() => {
loader.classList.remove("spinner-border");
}, 1000);
}
this is my code with what i have tried to add (on of the things i have tried.. this is the best output i could come with)
code:
// additional code to present to the user the error message if the input value is equal to 42.
clcBtn.addEventListener("click", errMsg);
function numValidateTwo(value) {
if(value === 42) {
return true;
}
return false;
}
function errMsg() {
if (!numValidateTwo (clcInput.value)) {
serverError.style.display = "block";
}
return;
}
a little bit more about what i am trying to achieve:
i want to present this error message to the user, whenever the input value is equal to 42.
is it related to async or callback? which i need to go through the lectures again.. but right now i need to solve this bec i have no time.
what did i do wrong ?
and how i can make it work?
can someone explain this to me?
thanks in advance!

How to execute node.js protoype function from html?

I have a program that will work to start a motion sensor when running the file from the command line, but when I try to call the function from HTML, it recognizes the prototype as 'undefined' and will not execute.
Here is the full code:
var sleep = require('sleep');
var Gpio = require('onoff').Gpio;
var LED = new Gpio(18, 'out');
var sensor = new Gpio(17, 'in', 'both');
sensor.watch(function(err, value){
if (err){
console.log('error');
exit();
}
if(value == 1) {
console.log('Motion Detected');
LED.writeSync(value);
sleep.sleep(3);
}
else if(value == 0) {
console.log('No Motion');
LED.writeSync(value);
sleep.sleep(3);
}
});
function exit() {
LED.unexport();
sensor.unexport();
process.exit();
}
dev tools says 'sensor' is undefined.
How do I run sensor.watch(callback) from html?
Thanks!

Retry when no response from website

I use the recursive function below, in order to reopen website if httpstatus != 200:
retryOpen = function(){
this.thenOpen("http://www.mywebsite.com", function(response){
utils.dump(response.status);
var httpstatus = response.status;
if(httpstatus != 200){
this.echo("FAILED GET WEBSITE, RETRY");
this.then(retryOpen);
} else{
var thisnow = hello[variable];
this.evaluate(function(valueOptionSelect){
$('select#the_id').val(valueOptionSelect);
$('select#the_id').trigger('change');
},thisnow);
}
});
}
The problem is that sometimes the retryOpen function does not even go as far as to callback function(response){}. Then, my script freezes.
I wonder how one could change the function to be able to recursively try to open website again if there is no response from website (not even some error code as 404 or something)? In other words, how to rewrite the retryOpen function so it reruns when the function does not reach callback after a certain amount of time?
I would try something like this. Please note this is untested code, but should get you on the correct path
retryOpen = function(maxretry){
var count = 0;
function makeCall(url)
{
this.thenOpen(url, function(response){
utils.dump(response.status);
});
}
function openIt(){
makeCall.call(this,"http://www.mywebsite.com");
this.waitFor(function check() {
var res = this.status(false);
return res.currentHTTPStatus === 200;
}, function then() {
var thisnow = hello[variable];
this.evaluate(function(valueOptionSelect){
$('select#the_id').val(valueOptionSelect);
$('select#the_id').trigger('change');
},thisnow);
}, function timeout() { // step to execute if check has failed
if(count < maxretry)
{
openIt.call(this);
}
count++
},
1000 //wait 1 sec
);
}
openIt();
}

Application infinite loop with processMessage failed error

My Cordova app not running in browser and mobile it shows an error
processMessage failed
Screenshot:
and goes infinite loop and it freezes the device any solution?
This question is already in asked here Cordova not running normally but there is not an answer so thats why I have to asked it again.
Getting the same issue (using Chrome with the phonegap desktop emulator. What I see as happening is this.
There seems to be a bug in Cordova.js that fails to check for an empty message.
When the app sends out alerts:
gap_init:2
gap:[0,"StatusBar","_ready","StatusBar1593157203"]
gap:[0,"App","show","App1593157204"]
gap:[0,"File","requestAllPaths","File1593157205"]
gap:[0,"NetworkStatus","getConnectionInfo","NetworkStatus1593157206"]
gap:[0,"Device","getDeviceInfo","Device1593157207"]
and you just hit 'OK', instead of clearing out the contents of that dialog box it going on to cause an infinite loooooop. I don't know the significance of these messages yes as I'm pretty new to Cordova, but it's hell and gone from the principle of least surprise!
So you can clear out the messages, or modify the cordova.js code where it gets stuck in the loop. You also could turn off the alerts that also works.
the function processMessage() (see below) doesn't test for an empty string, which in and of itself might be fine, but it is called from a while loop which only checks for "*" if its going to pop.
while (messagesFromNative.length) {
var msg = popMessageFromQueue();
// The Java side can send a * message to indicate that it
// still has messages waiting to be retrieved.
if (msg == '*' && messagesFromNative.length === 0) {
setTimeout(pollOnce, 0);
return;
}
processMessage(msg);
}
// Processes a single message, as encoded by NativeToJsMessageQueue.java.
function processMessage(message) {
try {
var firstChar = message.charAt(0);
if (firstChar == 'J') {
eval(message.slice(1));
} else if (firstChar == 'S' || firstChar == 'F') {
var success = firstChar == 'S';
var keepCallback = message.charAt(1) == '1';
var spaceIdx = message.indexOf(' ', 2);
var status = +message.slice(2, spaceIdx);
var nextSpaceIdx = message.indexOf(' ', spaceIdx + 1);
var callbackId = message.slice(spaceIdx + 1, nextSpaceIdx);
var payloadKind = message.charAt(nextSpaceIdx + 1);
var payload;
if (payloadKind == 's') {
payload = message.slice(nextSpaceIdx + 2);
} else if (payloadKind == 't') {
payload = true;
} else if (payloadKind == 'f') {
payload = false;
} else if (payloadKind == 'N') {
payload = null;
} else if (payloadKind == 'n') {
payload = +message.slice(nextSpaceIdx + 2);
} else if (payloadKind == 'A') {
var data = message.slice(nextSpaceIdx + 2);
var bytes = window.atob(data);
var arraybuffer = new Uint8Array(bytes.length);
for (var i = 0; i < bytes.length; i++) {
arraybuffer[i] = bytes.charCodeAt(i);
}
payload = arraybuffer.buffer;
} else if (payloadKind == 'S') {
payload = window.atob(message.slice(nextSpaceIdx + 2));
} else {
payload = JSON.parse(message.slice(nextSpaceIdx + 1));
}
cordova.callbackFromNative(callbackId, success, status, [payload], keepCallback);
} else {
console.log("processMessage failed: invalid message: " + JSON.stringify(message));
}
} catch (e) {
console.log("processMessage failed: Error: " + e);
console.log("processMessage failed: Stack: " + e.stack);
console.log("processMessage failed: Message: " + message);
}
}
Check your cordova js loading properly? is the path for cordova js is proper?
give path like this in your index.html:
<script type="text/javascript" src="cordova.js">
I had the problem in an Angular 6 project. It was simply solved by deleting cordova.js which was under src folder.
I was not able to resolve this issue when viewing the /android platform option for cordova serve; however, the /ios platform option did function properly.
Not much of a solution, but perhaps a mildly helpful workaround for those who follow.

PhantomJS / Javascript: write to file instead of to console

From PhantomJS, how do I write to a log instead of to the console?
In the examples https://github.com/ariya/phantomjs/wiki/Examples, it always (in the ones I have looked at) says something like:
console.log('some stuff I wrote');
This is not so useful.
The following can write contents to the file directly by phantomjs:
var fs = require('fs');
try {
fs.write("/home/username/sampleFileName.txt", "Message to be written to the file", 'w');
} catch(e) {
console.log(e);
}
phantom.exit();
The command in the answer by user984003 fails when there is some warning or exceptions occurred. And sometimes does not fall into our specific requirements because in some codebase I am getting the following message always which will also be logged to that file.
Refused to display document because display forbidden by X-Frame-Options.
So I figured it out:
>phantomjs.exe file_to_run.js > my_log.txt
You can override original console.log function, take a look at this :
Object.defineProperty(console, "toFile", {
get : function() {
return console.__file__;
},
set : function(val) {
if (!console.__file__ && val) {
console.__log__ = console.log;
console.log = function() {
var fs = require('fs');
var msg = '';
for (var i = 0; i < arguments.length; i++) {
msg += ((i === 0) ? '' : ' ') + arguments[i];
}
if (msg) {
fs.write(console.__file__, msg + '\r\n', 'a');
}
};
}
else if (console.__file__ && !val) {
console.log = console.__log__;
}
console.__file__ = val;
}
});
Then you can do this:
console.log('this will go to console');
console.toFile = 'test.txt';
console.log('this will go to the test.txt file');
console.toFile = '';
console.log('this will again go to the console');

Categories