Generate Logs For Web Application In Javascript
I have a use case in which I would like to generate logs for my JS web application, which could be stored as a file on the client-side (stored on the user's machine). Therefore, I
Solution 1:
You can use local storage to simulate file :
Create id for each line of your "file" and store the number of the last line
functionlogIntoStorage (pMsg) {
if (!pMsg) pMsg = "pMsg is not here !";
if ((typeof pMsg) != "string") pMsg = "pMsg is Not a string:"+(typeof pMsg);
let logNb = "logNb";
let padLong = 7;
let strLg = "0";
let lg = 0;
let maxSize = 50; // max nb of lines in the log// Reading log num line
strLg = localStorage.getItem(logNb);
if(!strLg) { //logNb not stored yet
lg = 0;
strLg = "0";
localStorage.setItem(logNb, lg.toString(10)); // store the number of cur line
} else { // Read logNb from storage
strLg = localStorage.getItem(logNb);
lg = parseInt(strLg,10);
}
if (lg >= maxSize) {
lg = maxSize; // size limit nb lines.
pMsg = "LIMIT SIZE REACHED";
}
// log msg into localStorage at logLine:0000#### let s = ("0000000000000000"+strLg).substr(-padLong); // padding zeroslocalStorage.setItem("logLine:"+s, pMsg);
if (lg >= maxSize) return;
lg++; // point to the next linelocalStorage.setItem(logNb, lg.toString(10));
}
Solution 2:
In modern Chrome you can actually "stream" data to the user's disk, after they give permission, thanks to the File System Access API.
To do so, you have to request for a file to save to, calling showSaveFilePicker()
.
Once you get the user's approval you'll receive a handle from where you'll be able to get a WriteableStream.
Once you are done writing, you just have to .close()
the writer.
onclick = async () => {
if( !("showSaveFilePicker"in self) ) {
thrownewError( "unsupported browser" );
}
const handle = awaitshowSaveFilePicker();
const filestream = await handle.createWritable();
const writer = await filestream.getWriter();
// here we have a WritableStream, with direct access to the user's disk// we can write to it as we wish
writer.write( "hello" );
writer.write( " world" );
// when we're done writingawait writer.ready;
writer.close();
};
Post a Comment for "Generate Logs For Web Application In Javascript"