I am attempting to submit a file with an HTML library using the IPFS Api. In order to do so I need to buffer the input before I add the file to IPFS.
My issue is that I have tried every option I've come across on the internet on how to resolve the error "Uncaught ReferenceError: buffer is not defined". I have reinstalled npm, Node, and used browserify with no success.
So what I did is I installed "npm install buffer" and went to the folder where index.js is located and used browserify to attempt to create a standalone buffer.js file.
browserify index.js -o buffer.js
I attempted to include the buffer.js file at the top of my HTML file and it changed the error to "require is not defined."
Here is my HTML code:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript file upload</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script src="./buffer.js"></script>
<script src="https://unpkg.com/ipfs-api#9.0.0/dist/index.js"
integrity="sha384-5bXRcW9kyxxnSMbOoHzraqa7Z0PQWIao+cgeg327zit1hz5LZCEbIMx/LWKPReuB"
crossorigin="anonymous"></script>
</head>
<script type="text/javascript">
function upload() {
const reader = new FileReader();
const buf = require('buffer');
reader.onloadend = function() {
const ipfs = window.IpfsApi('localhost', 5001) // Connect to IPFS
buf = buffer.Buffer(reader.result) // Convert data into buffer
ipfs.files.add(buf, (err, result) => { // Upload buffer to IPFS
if(err) {
console.error(err)
return
}
let url = `https://127.0.0.1:5001/ipfs/${result[0].hash}`
console.log(`Url --> ${url}`)
document.getElementById("url").innerHTML= url
document.getElementById("url").href= url
document.getElementById("output").src = url
})
}
const photo = document.getElementById("photo");
reader.readAsArrayBuffer(photo.files[0]); // Read Provided File
}
</script>
<body>
<form action="/">
<fieldset>
<legend>Upload photo</legend>
<input type="file" name="photo" id="photo">
<button type="button" onclick="upload()">Upload</button>
</fieldset>
</form>
</br>
</br>
<a id="url"></a>
</br>
</br>
<img id="output">
</body>
</html>
Here is what my project currently looks like:
How can I get the above code to work by recognizing "buffer" with a local HTML file to upload files to IPFS in Windows 10?
Related
I have a json file that I would like to fetch in javascript and create divs for it in the webpage.
My issue is that I am providing local path of the json file to the fetch method but it is adding it to the django webpage url.
The code below tries to fetch the local path of json file:
fetch('../../scrapers/jsonOutputs/linkedin_jobs.json')
.then(response => response.json())
.then(data => {
const jobListings = data.Jobs;
jobListings.forEach(job => {
const jobTitle = job["Job Title:"];
const employerName = job["Employer name: "];
const jobLocation = job["Job Location: "];
const jobDetails = job["Job Details: "];
const linkToJob = job["Link To Job: "];
const jobListingElement = document.createElement("div");
jobListingElement.classList.add("job-listing");
jobListingElement.innerHTML = `
<h2>${jobTitle}</h2>
<p>${employerName}</p>
<p>${jobLocation}</p>
<div class="job-description-container">
<div class="job-description">
<p>${jobDetails}</p>
View Job
</div>
</div>
`;
const jobListContainer = document.getElementById("job-list-container");
jobListContainer.appendChild(jobListingElement);
});
});
Now when I run the django webapp and inspect element the webpage, I get the following error
[Error] Failed to load resource: the server responded with a status of 404 (Not Found) (linkedin_jobs.json, line 0)
[Error] Unhandled Promise Rejection: SyntaxError: The string did not match the expected pattern.
promiseEmptyOnRejected (jobsearch-func.js:4)
promiseReactionJob
The inspect element shows
http://127.0.0.1:8000/scrapers/jsonOutputs/linkedin_jobs.json
which is problematic since this is not the path to my json file but instead its in my project folder.
How can I read the json file in javascript and create divs?
The code for running my javascript in my html page:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<h2 id="job-list-heading">Job Listings</h2>
<div id="job-list-container">
</div>
<script src={% static 'js/jobsearch-func.js' %}></script>
</body>
</html>
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.
I want to write a Javascript in a standard location and connect this file to a page html.
Write: (using Swift 1.2)
let path = NSTemporaryDirectory() + "foo.js"
var error: NSError?
text = "12345"
text.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding, error: &error)
html:
<html>
<head>
<script src="path/foo.js"></script>
</head>
<body>
<p> Use Foo </p>
</body>
Which path i can use?
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);
})
I get an error when i would like to render html file which contains a script link on js file.
But when i load page i get this error :
Started GET "/views/script.js" .... Returning 404
my folder is like this
|--todolist
|--main.go
|--views/
|--index.html
|--script.js
main.go
package main
import (
"github.com/zenazn/goji"
"html/template"
"net/http"
)
func renderHTMLPage(w http.ResponseWriter, path string) {
t, err := template.ParseFiles(path)
if err != nil {
panic(err)
}
t.Execute(w, nil)
}
func Index(w http.ResponseWriter, r *http.Request) {
renderHTMLPage(w, "./views/index.html")
}
func main() {
goji.Get("/", Index)
goji.Serve()
}
views/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Le titre du document</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="script.js"></script>
<h1>To-Do List </h1>
<ul id="todolist">
<li> Hello <button>Delete</button></li>
<li> Wesh <button>Delete</button></li>
</ul>
<input type="text" id="new-text" /><button id="add">Add</button>
</body>
</html>
views/script.js
function addListItem() {
var text = $('#new-text').val()
if (text != "") {
$('#todolist').append('<li>'+text+'<button id="dede" name=\"' + i + '\">Delete</button></li>')
}
$('#new-text').val("")
}
function deleteItem() {
$(this).parent().remove()
}
$(function() {
$('#add').on('click', addListItem);
$("#todolist").on("click", "#dede", deleteItem)
});
How can I do to make it properly load the js file ?
And what is the best way to create an app who use only jquery/javascript with a golang api on architecture ?
Thank you
You need to either:
Serve from the directory containing /views - e.g. goji.Get("/views/*", http.FileServer(http.Dir("/Users/matt/Desktop/views/")))`
Use http.StripPrefix (recommended)
The below allows you to decouple the path from the directory name:
func main() {
goji.Get("/views/*", http.StripPrefix("/views", http.FileServer(http.Dir("/Users/matt/Desktop/views/"))))
goji.Get("/", Index)
goji.Serve()
}
I'd recommend against serving from the 'root' - /*. Better to serve from a dedicated assets path as it makes it easier when looking at caching, interacting with CDNs, etc.
In this particular case code should look like
goji.Get("/", Index)
goji.Get("/*", http.FileServer(http.Dir("./views")))
goji.Serve()
But I must say keeping template and static files in same directory is bad idea as well as serving static files from root.