How to use FileSystem API to debug Javascript? The execution order issue
I was debugging a complicated program written in Javascript. I need to watch the change of a large matrix. It is not convenient to see each elements in the matrix using Chrome Inspect Element. So, I want to write the data into a text File. I found the FileSystem API and terminal.
I have integrate FileSystem API into my project, with refer to the FileSystem terminal project. And I defi开发者_如何转开发ne a global variable to store the fs.root . What I want is to pass this variable into my program when debugging, so I can dump data into text file using this fs.root. I request file system:
window.requestFileSystem(window.TEMPORARY, 5*1024*1024, onInitFs, errorHandler); // 5MB
But the "onInitFs" function seems like a message response function, which is called very late. Even after the "onLoad='MyFun();'". So, I do not know where to put my own function, to make sure that the variable "fs.root" is defined. Right now, I have put "MyFun()" to everywhere, all will generate an error that "fs.root" is not defined, since "onInitFs" function is not called. I have tested the calling sequence:
-------------main.html
<html>
<header>
<script type='text/javascript' src='MyFun.js'></script>
<script type='text/javascript' >
console.log('01Position');
function onInitFs(fs)
{
aGlobalFsRoot = fs.root;
console.log('04Position');
}
window.requestFileSystem(window.TEMPORARY, 5*1024*1024, onInitFs, errorHandler);
</script>
</header>
<body onLoad="MyFun();">
<script>
console.log('02Position');
</script>
</body>
</html>
-------------MyFun.js
var aGlobalFsRoot;
function MyFun()
{
console.log('03Position');
// want to use "aGlobalFsRoot" to dump some matrix data, but it is not defined, which means "onInitFs()" is still not called.
}
So, in the console window of Chrome Inspect Element: 01Position 02Position 03Position 04Position
can I enable the "onInitFun()" function called ealier than "MyFun()". Or Where should I put "MyFun()", so it can be called later than "onInitFun()". I do not want user to click one button, since MyFun just do pre-processing work when loading. May I generate one message, so "MyFun()" will be called later than "onInitFs()"?
Either Andrey's comment, or the following, should work:
window.requestFileSystem(window.TEMPORARY, 5*1024*1024, function(fs) {onInitFs(fs); MyFun(fs); } , errorHandler);
As I understand, the fs api is deliberately designed to be asynchronous. So you can't force it to be called in any order. So you would have to adjust to an asynchronous mindset instead of a synchronous mindset.
If you want MyFun
to be called when the file system request is done, then hook MyFun
to run when the file system request is done (and not to the other, irrelevent onBodyLoad
event):
精彩评论