I need to append file using HTML5 FileWriterSync, multiple blocks of data coming from server. I was tried to append but it was just writing a block of file only. Let's check my code.
var creator;
try {
fileEntry = fs.root.getFile(filename, {
create: creator
});
var byteArray = new Uint8Array(data.length);
for (var i = 0; i < data.length; i++) {
byteArray[i] = data.charCodeAt(i) & 0xff;
}
var BlobBuilderObj = new WebKitBlobBuilder();
BlobBuilderObj.append(byteArray.buffer);
if (!creator) fileEntry.createWriter().seek();
fileEntry.createWriter().write(BlobBuilderObj.getBlob())
} catch (e) {
errorHandler(e);
}
fs has been initialised before, creator changes for appending file and I need to append file.
My problem is how can I call seek to start writing from the EOF.
seek() takes an integer value for the offset. You need to set it to the file's length to do an append:
var fw = fileEntry.createWriter();
fw.seek(fw.length);
It should be similar to the async case:
http://www.html5rocks.com/en/tutorials/file/filesystem/#toc-file-appending
Related
My script is looking at json files created on the server and retrieved using
//this is the code that gets the JSON file
jQuery.get(link,data)
Alerting out 'data' shows the json text as valid:
{"menu":[{"link":"../chapter-1/index.html","title":"Chapter 1", "dl": "chapter-1"}
I try and parse the returned 'data' variable
obj = JSON.parse(data);
So that I can loop through it and do my additional tasks.
When I try and JSON.parse(data) it fails
//The loop
for (i = 0; i < obj.menu.length; i++) {
console.log(obj.menu[i].dl);
download_packet(obj.menu[i].dl, i);
}
When I add the json manually
obj = JSON.parse('{"menu":[{"link":"../chapter-1/index.html","title":"Chapter 1", "dl": "chapter-1"}]}');
It works.
I have tried to convert to string etc.
Anyone know what I am stuffing up? - There are no error messages in the console.
This is the whole snippet:
function download_items(link) {
jQuery.get(link, function(data) {
var obj = data;
var i;
for (i = 0; i < obj.menu.length; i++) {
console.log(obj.menu[i].dl);
}
});
}
#Malcolm Mclean - put me on the right track.I converted my object to string then parsed it and it worked. A bit inefficient but its working.
Thanks Mal!
The JSON had to be parsed correctly:
jQuery.get(link, function(data) {
var obj = String(json_object);
obj = JSON.parse(json_object);
}
I'm trying to create a .zip file from a JSON object in Node.js. I'm using adm-zip to do that however I'm unable to make it work with this code:
var admZip = require('adm-zip');
var zip = new admZip();
zip.addFile(Date.now() + '.json', new Buffer(JSON.stringify(jsonObject));
var willSendthis = zip.toBuffer();
fs.writeFileSync('./example.zip', willSendthis);
This code creates example.zip but I'm not able to extract it, I tried with a .zipextractor but also with this code:
var admZip = require('adm-zip');
var zip = new admZip("./example.zip");
var zipEntries = zip.getEntries(); // an array of ZipEntry records
zipEntries.forEach(function(zipEntry) {
console.log(zipEntry.data.toString('utf8'));
});
It returns Cannot read property 'toString' of undefined at the line with console.log.
I could use zip.writeZip() for this example but I'm sending the .zipfile to Amazon S3 thus I need to use the method .toBuffer() to do something like this after using adm-zip:
var params = {Key: 'example.zip', Body: zip.toBuffer()};
s3bucket.upload(params, function(err, data) {...});
I don't see what is wrong, am I using the package correctly?
Try use zipEntry.getData().toString('utf8') instead zipEntry.data.toString('utf8'):
var admZip = require('adm-zip');
var zip = new admZip("./example.zip");
var zipEntries = zip.getEntries(); // an array of ZipEntry records
zipEntries.forEach(function(zipEntry) {
console.log(zipEntry.getData().toString('utf8'));
});
I have a Cloud Code script that pulls some JSON from a service. That JSON includes an array of objects. I want to save those to Parse, but using a specific Parse class. How can I do it?
Here's my code.
Parse.Cloud.httpRequest({
url: 'http://myservicehost.com',
headers: {
'Authorization': 'XXX'
},
success: function(httpResponse) {
console.log("Success!");
var json = JSON.parse(httpResponse.text);
var recipes = json.results;
for(int i=0; i<recipes.length; i++) {
var Recipe = Parse.Object.extend("Recipe");
var recipeFromJSON = recipes[i];
// how do i save recipeFromJSON into Recipe without setting all the fields one by one?
}
}
});
I think I got it working. You need to set the className property in the JSON data object to your class name. (Found it in the source code) But I did only try this on the client side though.
for(int i=0; i<recipes.length; i++) {
var recipeFromJSON = recipes[i];
recipeFromJSON.className = "Recipe";
var recipeParseObject = Parse.Object.fromJSON(recipeFromJSON);
// do stuff with recipeParseObject
}
Example from this page https://parse.com/docs/js/guide
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
gameScore.save({
score: 1337,
playerName: "Sean Plott",
cheatMode: false
}, {
success: function(gameScore) {
// The object was saved successfully.
},
error: function(gameScore, error) {
// The save failed.
// error is a Parse.Error with an error code and message.
}
});
IHMO this question is not a duplicate of How to use Parse.Object fromJSON? [duplicate]
In this question the JSON has not been generated by the Parse.Object.toJSON function itself, but comes from another service.
const object = new Parse.Object('MyClass')
const asJson = object.toJSON();
// asJson.className = 'MyClass';
Parse.Object.fromJSON(asJson);
// Without L3 this results into:
// Error: Cannot create an object without a className
// It makes no sense (to me) why the Parse.Object.toJSON is not reversible
I want to add three files simulteneously.Files with extension kml,kmz and csv.
When I select all three files and click open I get all three files in FileList.
But only one file is getting added on map.If I add individual file i.e. one by one it works fine. reader onloadend event is fired 3 times.But all the time it adds only one of the three files.
function handleFileSelect(evt) {
var files = evt.target.files; // FileList
for (var i = 0; i < files.length; i++) {
f = files[i];
fileExtension = f.name.split('.').pop();
if(fileExtension != 'kml' && fileExtension !='kmz' && fileExtension != 'csv'){
alert('Unsupported file type ' + f.type + '(' + fileExtension + ')');
return;
}
var fileReaderkmlcsv = new FileReader();
fileReaderkmlcsv.readAsText(f);
fileReaderkmlcsv.onloadend =loadend;
} //- end for loop } //handleFileSelect
The problem was asynchronous code execution in javascript.
Here is the answer-
Asynchronous execution in javascript any solution to control execution?
In the following example (yes, I am coding on my timeline while I try to work this out - I know, I know) I am loading an SWF in an HTML page and then directing the SWF to get the query parameters from the current URL. The query parameter will contain the source for the video to play.
This seems straight forward to me but I cannot get myURL = urlVars.videoloc; to work. More specifically, urlVars.videoloc seems to be undefined rather than holding the query parameter from the URL. All other variables are correct; both wholeURL and urlVars are defined.
//Initialize Global Event Listener
player.addEventListener(Event.ADDED_TO_STAGE, getPlay, false, 0, true);
//Function to play the video
function getPlay(e:Event):void {
var wholeURL:String = ExternalInterface.call("window.location.search.toString");
var urlVars:URLVariables = new URLVariables(wholeURL);
var myURL:String = urlVars.videoloc; //<--- Trouble, returning 'undefined'
errorBox.text = "videoloc="+urlVars.videoloc+"\nwholeURL="+wholeURL+"\nurlVars="+urlVars+"\nmyURL="+myURL; //<--- The reason I know it is returning 'undefined'
if (myURL) {
player.load(myURL);
player.play();
}
}
Ideally you should use a debugger to inspect the makeup of your URLVariables object.
If you're unable to do things the easy way, you could do this to trace its contents:
for (var parameter:String in urlVars) {
trace(parameter + "=" + urlVars[parameter]);
}
As you can see, you can step through every parameter inside urlVars using a for in loop.
I'm guessing videoLoc is your first parameter? Look at the results of this test of mine:
var address:String = "http://www.google.ca/search?q=test&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-GB:official&client=firefox-a";
var urlVars:URLVariables = new URLVariables(address);
for (var parameter:String in urlVars) {
trace(parameter + "=" + urlVars[parameter]);
}
The output of this is:
aq=t
rls=org.mozilla:en-GB:official
client=firefox-a
http://www.google.ca/search?q=test
ie=utf-8
oe=utf-8
See what happened to the q parameter? To fix this, use only the text past the ?
var address:String = "http://www.google.ca/search?q=test&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-GB:official&client=firefox-a";
var urlVars:URLVariables
= new URLVariables(address.substr(address.indexOf('?')+1));
for (var parameter:String in urlVars) {
trace(parameter + "=" + urlVars[parameter]);
}