I am trying to learn how to use sql.js from here. https://sql.js.org/#/
I am following there first html example and I keep coming across errors just trying to run this.
I installed sql.js using npm install sql.js
I took the dist folder from the sql.js install and put it into the test folder where the index.html is.
I used there example code and tried open it in a browser but I am faced with: sql-wasm.js:167 Fetch API cannot load file:///C:/dist/sql-wasm.wasm. URL scheme "file" is not supported.
Code:
<meta charset="utf8" />
<html>
<script src='C:\\Users\\Rocko\\Documents\\scripts\\AAOA\\nodetest\\dist\\sql-wasm.js'></script>
<script>
config = {
locateFile: filename => `/dist/${filename}`
}
// The `initSqlJs` function is globally provided by all of the main dist files if loaded in the browser.
// We must specify this locateFile function if we are loading a wasm file from anywhere other than the current html page's folder.
initSqlJs(config).then(function(SQL){
//Create the database
const db = new SQL.Database();
// Run a query without reading the results
db.run("CREATE TABLE test (col1, col2);");
// Insert two rows: (1,111) and (2,222)
db.run("INSERT INTO test VALUES (?,?), (?,?)", [1,111,2,222]);
// Prepare a statement
const stmt = db.prepare("SELECT * FROM test WHERE col1 BETWEEN $start AND $end");
stmt.getAsObject({$start:1, $end:1}); // {col1:1, col2:111}
// Bind new values
stmt.bind({$start:1, $end:2});
while(stmt.step()) { //
const row = stmt.getAsObject();
console.log('Here is a row: ' + JSON.stringify(row));
}
});
</script>
<body>
Output is in Javascript console
</body>
</html>
Pictures:
I have been trying to have my test webapp read my sqlite file for about 2 weeks now and I have been trying to follow what people have suggested. This is the latest suggestion and so I am trying to learn this but I can't even get the basic example done.
Any ideas would be appreciated.
Thanks
I had the same error following the same page in the sql.js documentation.
The error is avoided by using sql-asm.js instead of sql-wasm.js. As the document says further down the page: "sql-asm.js The older asm.js version of Sql.js. Slower and larger. Provided for compatibility reasons."
This is preferable for me than spinning up a web server or trying to "encode the wasm as base64" as some other threads suggest (which is way beyond me while just trying to create a simple stand-alone .html page linked to a sqlite file).
You are trying to load the WASM file from a local file, which does not work.
But you can easily just spin up a webserver (by using e.g. NodeJS) on your local machine, and then run your test code from there, so it accesses it using a proper URL instead of a local file on your PC.
Related
im trying to make a js app that tells someone to log in and saves the email and password in a text file, after some googling it looks like js doesn't have access to system files so node is required.
so i searched how to do it, but i keep getting an error that says Uncaught ReferenceError: require is not defined at HTMLButtonElement
this is the JS code:
let email = document.querySelector(".txt");
let password = document.querySelector(".pass");
let log_btn = document.querySelector("button");
log_btn.addEventListener("click", () => {
let mail = email.value;
let pass = password.value;
var fs = require('fs');
let content = `email: ${mail}\n password: ${pass}`;
fs.writeFile("info.txt", content, err => {
if (err) {
console.error(err);
return;
}
console.log("file created");
});
window.location.href = "index2.html"
})
what is preventing this from working, is there something i should include or install or anything.
hope someone has the answer, thanks in advance.
NodeJS is not a thing for browsers, it's a console application (the one outputting white text in black window)
To work with HTML and NodeJS at once, you need to use a mix of NodeJS and Browser, like https://nwjs.io/ or https://www.electronjs.org/
Download NWJS, upzip it, and open the HTML file with nw.exe, then you'll get a browser where you can use require and use filesystem
If the thing you want is making a web page which connects to a server that saves the file that's another thing, see https://adevait.com/nodejs/build-a-crud-app-with-only-json-files for example
1 - If you are trying to write a file on client machine, You can't do this in any cross-browser way. IE does have methods to enable "trusted" applications to use ActiveX objects to read/write file.
2 - If you are trying to save it on your server then simply pass on the text data to your server and execute the file writing code using some server side language.
3 - To store some information on the client side that is considerably small, you can go for cookies.
4 - Using the HTML5 API for Local Storage.
I am trying to read a project file that will be updated(occasionally) by me and my website will read it dynamically upon the loading of the page, will i have to build a server for this or can javascript handle it?
If so, could you share code that could achieve this.
Thanks in advance!!!
The problem seems to be how can one:
read a plaintext file stored on the website's local directory
use the contents of the file to modify a web page's content
This could be handled with JavaScript on the server side, but only if the server is configured to run JavaScript (like a node.js server).
Since the original question reads "will i have to build a server for this", it's probably likely that this is a vanilla server like Apache.
Most Apache servers are configured to run PHP code, so PHP is probably the simplest solution for grabbing the plaintext file.
Code below will load the contents of a plaintext file on the server into a JavaScript string, which then can be acted upon in the browser with JavaScript.
This code would go inside a <script> element in the HTML file:
function actUponProjectFile () {
// read project file on server using PHP, and store into JavaScript
// constant `projectFileString`
const projectFileString = `<?php
$pfText = file_get_contents('./my_project_file.txt');
echo $pfText; ?>`;
// insert code to act upon the `projectFileString` here
}
// run `actUponProjectFile()` after the window loads
window.onload = () => {
actUponProjectFile();
}
Save your data in a Javascript file and include it in your html
// data.js
const data = [
{
type: 'airtime',
price: 20,
size: '5GB',
},
{
type: 'electricity',
price: 10,
size: '40mw',
},
];
Then include the file in your html file
<script type="text/javascript" src="data.js"></script>
You can use nginx to share static files and use fetch request in js to get this file from server. If you have only static files you don't need to use server, nginx will be enough for you.
So I'm relatively new to JavaScript and I'm attempting to learn OpenCV.js for a web app I'm working on. I've been following tutorials like this to try and understand how it works.
However, I've been getting the error below where the haar cascade file isn't being loaded and I can't seem to fix it.
Error: Assertion failed (!empty()) in detectMultiScale, file /build/master-contrib_docs-lin64/opencv/modules/objdetect/src/cascadedetect.cpp
I've looked for resolutions to this problem and most people suggest that you should use the full directory when loading a cascade file. I've tried referencing the file directly and using the full file path, either way doesn't seem to work for me.
This is how I've attempted load the file.
let classifier = new cv.CascadeClassifier();
// Load the haarcascade file
let utils = new Utils('errorMessage');
let faceCascadeFile = 'http://localhost/eeu8cb/xml/haarcascade_frontalface_default.xml';
utils.createFileFromUrl(faceCascadeFile, faceCascadeFile, () => {
classifier.load(faceCascadeFile)
});
// Checks if the haarcascade file has failed to load
if(!classifier.load(faceCascadeFile)){
console.log('failed to load file.')
}
I've done some error checking which confirms the file isn't being loaded. Any help would be appriciated, cheers.
Some month ago i worked right on OpenCV.js using those tutorials and i remember there was a problem on loading files while not using HTTPS protocol, i solved my problem using IIS Express.
So try using a web server.
Problem definition:
I am programming one HTML file to be run locally in a user machine NOT FUNCTIONING AS A SERVER.
A user could run this html file locally stored in his computer. The HTML file will generate a table dynamically based on the data stored in his machine locally in a particular folder (which is always the same). This data is a JSON file.
For clarity reasons asume that the JSON file is in the same folder as the HTML file.
I have been reading a lot in the internet and in stack overflow at no avail.
For instance:
a) here with:
$.getJSON("books.json", function(json) {
console.log(json);
//access your JSON file through the variable "json"
});
does not work.
Or using this code:
jQuery.getJSON("data.json", handleJSON);
function handleJSON(result){
jQuery.each(result, printFields);
}
function printFields(i, field){
let row = field.id + " "+field.first_name + " "+field.last_name + " <br>";
jQuery("div").append(row);
}
the console says:
[Error] Failed to load resource: Preflight response is not successful (data.json, line 0)
[Error] XMLHttpRequest cannot load file:///Users/jose/CODE/HTML/ConceptsHTML/example%203/data.json. Preflight response is not successful
There are several other links of Stack overflow that I could put here. None one functions as smoothly as they say they do.
(I am using a MAC and trying the HTMLs in Safari and Chrome)
Ultimately I want of course to pass the JSON to an array to be access in other scripts of the HTML.
Note: There are some solutions where it is said that the local machine has to be run as a server and an Httprequest should be done in the machine. Well I can not do that since the users can only open the html file but nothing can be expected from them as to set the machine as as ever whatsoever.
I would be very very glad If I get a hint as to how to proceed. Right now I don't even know if this is actually possible to do.
thanks a lot
You could just use another JS file and link to it in your HTML file, and then in that JS file just make an object with the data you want.
HTML:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="json.js"></script>
<script type="text/javascript">
function fun(){
alert(json.data);
}
</script>
</head>
<body>
<button onclick="fun();">push me</button>
</body>
</html>
JS (json.js):
var json = {
data : "hello world"
};
Linking to a local JSON file cannot be done.
THE ANSWER IS:
IT IS NOT POSSIBLE TO READ LOCAL FILES (FILES IN THE USER MACHINE) WITH HTML DUE TO SECURITY REASONS.
The funny thing is that there are plenty of post telling the contrary.
I UNDERSTAND THAT IF THAT WOULD BE POSSIBLE SENSIBLE DATA MIGHT BE STOLEN.
The improvement for html future versions would be to create a way for the local. User to tell the local browser which local folder is "free" to be accesible by html.
At first, you need to parse loaded json file, because before parsing, the content is just string and you can not handle it.
So please do as below:
function handleJSON(result){
result = JSON.parse(result); // using json.parse function to convert string to a valid json model.
jQuery.each(result, printFields);
}
I hope it will be helped you.
I've converted an existing web application (HTML5, JS, CSS, etc.) into a Windows UWP app so that (hopefully) I can distribute it via the Windows Store to Surface Hubs so it can run offline. Everything is working fine, except PDF viewing. If I open a PDF in a new window, the Edge-based browser window simply crashes. If I open an IFRAME and load PDFJS into it, that also crashes. What I'd really like to do is just hand off the PDF to the operating system so the user can view it in whatever PDF viewer they have installed.
I've found some windows-specific Javascript APIs that seem promising, but I cannot get them to work. For example:
Windows.System.Launcher.launchUriAsync(
new Windows.Foundation.Uri(
"file:///"+
Windows.ApplicationModel.Package.current.installedLocation.path
.replace(/\//g,"/")+"/app/"+url)).then(function(success) {
if (!success) {
That generates a file:// URL that I can copy into Edge and it shows the PDF, so I know the URL stuff is right. However, in the application it does nothing.
If I pass an https:// URL into that launchUriAsync function, that works. So it appears that function just doesn't like file:// URLs.
I also tried this:
Windows.ApplicationModel.Package.current.installedLocation.getFileAsync(url).then(
function(file) { Windows.System.Launcher.launchFileAsync(file) })
That didn't work either. Again, no error. It just didn't do anything.
Any ideas of other things I could try?
-- Update --
See the accepted answer. Here is the code I ended up using. (Note that all my files are in a subfolder called "app"):
if (location.href.match(/^ms-appx:/)) {
url = url.replace(/\?.+/, "");
Windows.ApplicationModel.Package.current.installedLocation.getFileAsync(("app/" + url).replace(/\//g,"\\")).then(
function (file) {
var fn = performance.now()+url.replace(/^.+\./, ".");
file.copyAsync(Windows.Storage.ApplicationData.current.temporaryFolder,
fn).then(
function (file2) {
Windows.System.Launcher.launchFileAsync(file2)
})
});
return;
}
Turns out you have to turn the / into \ or it won't find the file. And copyAsync refuses to overwrite, so I just use performance.now to ensure I always use a new file name. (In my application, the source file names of the PDFs are auto-generated anyway.) If you wanted to keep the filename, you'd have to add a bunch of code to check whether it's already there, etc.
LaunchFileAsync is the right API to use here. You can't launch a file directly from the install directory because it is protected. You need to copy it first to a location that is accessible for the other app (e.g. your PDF viewer). Use StorageFile.CopyAsync to make a copy in the desired location.
Official SDK sample: https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/AssociationLaunching
I just thought I'd add a variation on this answer, which combines some details from above with this info about saving a blob as a file in a JavaScript app. My case is that I have a BLOB that represents the data for an epub file, and because of the UWP content security policy, it's not possible simply to force a click on a URL created from the BLOB (that "simple" method is explicitly blocked in UWP, even though it works in Edge). Here is the code that worked for me:
// Copy BLOB to downloads folder and launch from there in Edge
// First create an empty file in the folder
Windows.Storage.DownloadsFolder.createFileAsync(filename,
Windows.Storage.CreationCollisionOption.generateUniqueName).then(
function (file) {
// Open the returned dummy file in order to copy the data to it
file.openAsync(Windows.Storage.FileAccessMode.readWrite).then(function (output) {
// Get the InputStream stream from the blob object
var input = blob.msDetachStream();
// Copy the stream from the blob to the File stream
Windows.Storage.Streams.RandomAccessStream.copyAsync(input, output).then(
function () {
output.flushAsync().done(function () {
input.close();
output.close();
Windows.System.Launcher.launchFileAsync(file);
});
});
});
});
Note that CreationCollisionOption.generateUniqueName handles the file renaming automatically, so I don't need to fiddle with performance.now() as in the answer above.
Just to add that one of the things that's so difficult about UWP app development, especially in JavaScript, is how hard it is to find coherent information. It took me hours and hours to put the above together from snippets and post replies, following false paths and incomplete MS documentation.
You will want to use the PDF APIs https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/PdfDocument/js
https://github.com/Microsoft/Windows-universal-samples/blob/master/Samples/PdfDocument/js/js/scenario1-render.js
Are you simply just trying to render a PDF file?