How to read hdf5 file in javascript inside browser - javascript

I have hdf5 file created using c++ application.i want to read the same hdf5 file inside browser using javascript.
Hdf5 file will be download from server using xhr or web socket request and the content of the file will be stored in javascript variable then i want to read the content of the variable.
Please tell me any javascript library available to read the hdf5 inside browser.
i tried "https://github.com/HDF-NI/hdf5.node" but it supports only for nodejs.
Is it possible to convert the above library to support reading inside browser.

It is only able to read a subset of HDF5 files, but this is something that works:
https://github.com/usnistgov/jsfive
It basically covers all the files that can be read by the pyfive library (https://github.com/jjhelmus/pyfive), as it is a direct port of that library.

The best two libraries that I found are jsfive and h5wasm:
Sample code jsfive:
$(document).ready(function() {
$("#datafile").change(async function loadData() {
var file_input = $("#datafile")[0];
var file = file_input.files[0]; // only one file allowed
let datafilename = file.name;
let reader = new FileReader();
reader.onloadend = function(evt) {
let barr = evt.target.result;
var f = new hdf5.File(barr, datafilename);
let value = f.get('main').value
let attrs = f.get('main').attrs
// do somthing with f
}
})
})
<!DOCTYPE html>
<html lang="eng">
<head>
</head>
<body>
<input type="file" id="datafile" name="file">
<!-- Import JQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<!-- Import JSFive -->
<script src="https://cdn.jsdelivr.net/npm/jsfive#0.3.7/dist/hdf5.js">
<!-- Import main JS -->
<
script src = "app.js" >
</script>
</body>
</html>
Sample code h5wasm:
import * as hdf5 from "https://cdn.jsdelivr.net/npm/h5wasm#latest/dist/esm/hdf5_hl.js";
await hdf5.ready;
$(document).ready(function() {
$("#datafile").change(async function loadData() {
let file = $("#datafile")[0].files[0];
let data_filename = file.name;
let ab = await file.arrayBuffer();
hdf5.FS.writeFile(data_filename, new Uint8Array(ab));
let f = new hdf5.File(data_filename, "r");
// do somthing with f
f.close()
})
})
<!DOCTYPE html>
<html lang="eng">
<head>
</head>
<body>
<input type="file" id="datafile" name="file">
<!-- Import JQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<!-- Import main JS -->
<script type="module" src="app.js" ></script>
</body>
</html>
Also interesting jsfive with callback:
function storeTarget(result, file_name) {
f = new hdf5.File(result, file_name);
}
$("#datafile").change(async function loadSource() {
var file_input = $("#datafile")[0];
var file = file_input.files[0];
let datafilename = file.name;
const reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = () => storeTarget(reader.result, datafilename);
})

Related

calling the next javascript via eval, remove the span tag created by the initial JS file

I have a html file and 2 JavaScript files: mainscript.js and script1.js. I inject the script1.js inside the mainscript.js. However, what happens is that by calling script1.js, the htmltags created by mainscript.js got removed. Any idea why this happens?
html code:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Linear Call</title>
</head>
<body>
<div id="main"><p>hi</p></div>
<script src="js/recursion_linear/MainScript.js">
</script>
</body>
</html>
mainscript.js:
const loadScript = async(url) => {
const response = await fetch(url)
const script = await response.text()
eval(script)
}
var s = document.createElement("span");
document.write("<br>");
s.innerText="This is main script";
s.id="mainscript";
document.body.append(s);
const scriptUrl_1 = "js/recursion_linear/Script1.js"
loadScript(scriptUrl_1)
script1.js:
document.write("<br>");
var s = document.createElement("span");
s.innerText="This is Script1";
s.id="script1";
document.body.append(s);
The output is
This is Script1
While the expected one is
This is main script
This is Script1

Load and process 3D image volume saved in hdf5 file format via vanilla JS

How can I load and process a 3D image volume, saved as an hdf5 file, directly in the frontend using JS?
This can be achieved using jsfive and numjs.
The following code cuts an 124x124 image, at z=10, y0=0, y1=124, x0=0, x1=124, from a volume of dimension 20x1400x700 (z,y,x). The 3D volume is stored in the h5 file under the key 'main'. The implementation uses a callback that provides more flexibility and makes the h5 file available outside the async function.
$(document).ready(function() {
$("#datafile").change(async function loadData() {
const reader = new FileReader();
let file = $("#datafile")[0].files[0]
let file_name = file.name
reader.readAsArrayBuffer($("#datafile")[0].files[0]);
reader.onload = () => storeResults(reader.result, file_name);
})
// callback function
function storeResults(result, file_namet) {
f = new hdf5.File(result, file_namet);
let array = f.get('main').value
// jsfive can only return 1D arrays from a read operation -> use numjs to reconstruct the 3D volume
array = nj.array(array).reshape(20, 1400, 700)
// slicing a 124x124 image from the volume
// use reshape to drop the channel dimension 1x124x124 -> 124x124
let img = array.slice([10, 11], [0, 124], [0, 124]).reshape(124, 124)
// convert to image and save to canvas
let resized = nj.images.resize(img, 124, 124)
let $original = document.getElementById('original');
$original.width = 124;
$original.height = 124;
nj.images.save(resized, $original);
console.log("done")
}
})
<!DOCTYPE html>
<html lang="eng">
<head>
<!-- Import JQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<!-- Import JSFive -->
<script src="https://cdn.jsdelivr.net/npm/jsfive#0.3.7/dist/hdf5.js"></script>
<!-- Import NumJs-->
<script src="https://cdn.jsdelivr.net/gh/nicolaspanel/numjs#0.15.1/dist/numjs.min.js"></script>
</head>
<body>
<div>
<h3>Original image (h<span id="h"></span>, w<span id="w"></span>)</h3>
<canvas id="original" width=64 height=64></canvas>
</div>
<input type="file" id="datafile" name="file">
<!-- Import main JS -->
<script src="app.js"></script>
</body>
</html>

load markdown file from http directory into javascript string

I need some javascript code to read a "markdown file" from my http directory and place it into a javascript string. How would I modify this code to do that?
<!-- FILE: index.html-->
<!DOCTYPE html>
<html>
<head>
<title>Markdown TexDollar Reader</title>
<!-- Javascript setup using node.js: ->
<!-- C:\demo> npm install mathjax -->
<!-- C:\demo> npm install showdown -->
<script type="text/javascript" src="./node_modules/showdown/dist/showdown.js"></script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [["$","$"],["\\(","\\)"]]}
});
</script>
<script type="text/javascript"
src="./node_modules/mathjax/MathJax.js?config=TeX-AMS_HTML-full"></script>
</head>
<body>
<script>
converter = new showdown.Converter();
<!-- FIXME: Instead of setting text string manually from javascript,
i want to load my file
in http directory called "markdown.md" into the javascript string text-->
text = '# hello, markdown!';
text += '\nthis is a test';
text += '\n$$e=mc^2$$';
html = converter.makeHtml(text);
document.write(html);
</script>
</body>
</html>
The only way to load a text file locally without an http server is to use the HTML5 api for loading a file through a file dialog where the use selects a markdown file to read:
<!DOCTYPE html>
<html>
<head>
<title>Render "Markdown file with Tex-Dollar" in browser</title>
<!-- node.js packages required: -->
<!-- npm install jquery -->
<!-- npm install showdown -->
<!-- npm install mathjax -->
<script type="text/javascript" src="./node_modules/showdown/dist/jquery.js"></script>
<script type="text/javascript" src="./node_modules/showdown/dist/showdown.js"></script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [["$","$"],["\\(","\\)"]]}
});
</script>
<script type="text/javascript"
src="./node_modules/mathjax/MathJax.js?config=TeX-AMS_HTML-full"></script>
<script type="text/javascript">
var reader;
function checkFileAPI() {
if (window.File && window.FileReader && window.FileList && window.Blob) {
reader = new FileReader();
return true;
} else {
alert('The File APIs are not fully supported by your browser. Fallback required.');
return false;
}
}
function readText(filePath) {
var output = ""; //placeholder for text output
if(filePath.files && filePath.files[0]) {
reader.onload = function (e) {
output = e.target.result;
displayContents(output);
};//end onload()
reader.readAsText(filePath.files[0]);
}//end if html5 filelist support
else if(ActiveXObject && filePath) { //fallback to IE 6-8 support via ActiveX
try {
reader = new ActiveXObject("Scripting.FileSystemObject");
var file = reader.OpenTextFile(filePath, 1); //ActiveX File Object
output = file.ReadAll(); //text contents of file
file.Close(); //close file "input stream"
displayContents(output);
} catch (e) {
if (e.number == -2146827859) {
alert('Unable to access local files due to browser security settings. ' +
'To overcome this, go to Tools->Internet Options->Security->Custom Level. ' +
'Find the setting for "Initialize and script ActiveX controls not marked as safe" and change it to "Enable" or "Prompt"');
}
}
}
else { //this is where you could fallback to Java Applet, Flash or similar
return false;
}
return true;
}
function displayContents(txt) {
converter = new showdown.Converter();
html = converter.makeHtml(txt);
var el = document.getElementById('main');
el.innerHTML = html; //display output in DOM
MathJax.Hub.Queue(["Typeset",MathJax.Hub, "main"]);
}
</script>
</head>
<body onload="checkFileAPI();">
<div id="container">
<input type="file" onchange='readText(this)' />
<br/>
<hr/>
<h3>Contents of the Text file:</h3>
<div id="main">
...
</div>
</div>
</body>
</html>
The mathjax rendering is a little flaky when loading from markdown... if anybody knows how to fix it. let me know. thanks.

how to call one file input id into another file using javascript

im having 2 html files, in my first file i have declared a variable and i want to use the same variable in my second file...
my first file code is
<script type="text/javascript">
function topics(clicked_id)
{
var ids = clicked_id;
var myObject, fol;
myObject = new ActiveXObject("Scripting.FileSystemObject");
if(!myObject.FolderExists("D:/JavaScript/Work/Days/"+ids))
{
fol = myObject.CreateFolder("D:/JavaScript/Work/Days/"+ids);
}
load_page();
}
function load_page()
{
open("file:///D:/JavaScript/Work/Topics_Page.html");
}
</script>
i want to use "ids" variable in my second file...
Thanks;
If the HTML documents have the same origin you can use postMessage, MessageChannel, SharedWorker or storage event to communicate between different browsing contexts, see
How can I load a shared web worker with a user-script?
Can we refer to JavaScript variables across webpages in a browser session?
how to pass data from one html page to second in php?
You can use localStorage and storage event to use the same object variable, or define a local variable set to the value of localStorage at a different HTML documenta having the same domain.
<!DOCTYPE html>
<html>
<head>
<title>index</title>
</head>
<body>
otherPage.html
<h1>set id</h1>
<script>
let id;
let h1 = document.querySelector("h1");
h1.onclick = e => {
id = `${Math.E * Math.PI * Math.random()}`;
localStorage.setItem("id", id);
console.log(`id: ${id} at ${e.type}`);
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>other page</title>
<script>
let id = localStorage.getItem("id");
console.log(`id: ${id} at ${document.title}`);
onstorage = e => {
console.log(`id: ${localStorage.getItem("id")} at ${e.type}`);
id = localStorage.getItem("id");
console.log(id);
}
</script>
</head>
<body>
<h1>otherPage.html</h1>
</body>
</html>
plnkr https://plnkr.co/edit/m4RIdwgIl74Dk6YmGAgI?p=preview

To Get Some lines from indx.html to another text.html

With the help of following code i will get the 100% ok result but if i need to trigger the same as automatic how it is possible.
<!DOCTYPE html>
<html>
<head>
<title>reading file</title>
<script type="text/javascript">
var reader = new FileReader();
function readText(that){
if(that.files && that.files[0]){
var reader = new FileReader();
reader.onload = function (e) {
var output=e.target.result;
//process text to show only lines with "li class="Body-P-P1":
output=output.split("\n").filter(/./.test, /\li class="Body-P-P1"/).join("\n");
document.getElementById('main').innerHTML= output;
};//end onload()
reader.readAsText(that.files[0]);
}//end if html5 filelist support
}
</script>
</head>
<body>
<input type="file" onchange='readText(this)' />
<div id="main"></div>
</body>
</html>
Kindly let me know the way i run the above code automatically trigger whenever i click on any programe which contain the same code.

Categories

Resources