I cannot install sql.js properly - javascript

I'm trying to create a database on the client-side using sql.js and vanilla js. I guess, there is some problem within the installation process. I've done the 'npm install sql.js' and included the CDN. I get this error from the console 'Uncaught ReferenceError: require is not defined'
(BTW this my first question on here, open to suggestions...)
This is pretty much the expression shown in the documentation on their website. I can't make it work, though. Is it because of node.js or something else?
<script type="module">
const initSqlJs = require('/sql.js');
const SQL = await initSqlJs({
locateFile: (file) =>
'https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.8.0/sql-wasm.js',
});
const db = new SQL.Database();
let sqlstr =
"CREATE TABLE hello (a int, b char); \
INSERT INTO hello VALUES (0, 'hello'); \
INSERT INTO hello VALUES (1, 'world');";
db.run(sqlstr);
</script>
file tree

I've done some research considering your comments. I should've used the sql-asm.js instead of sql-wasm.js because I don't need to use 'web-assembly'. Yet, they have sql-wasm.js in their example code, which I still do not understand. Modifying this and not using require() solved my issue.
<meta charset="utf8" />
<html>
<script src="node_modules/sql.js/dist/sql-asm.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>

Related

Why can i not create a Connex object with js in my flutter project

Im currently developing a dApp and want to connect it with the sync2 wallet. Since there is no support for dart im trying to use js functions in a js file in in the web-folder like this:
function checkBalance(value) {
const connex = new Connex({
node: 'http://3.71.71.72:8669/',
network: 'test'
})
const queryAcc = value
const acc = connex.thor.account(queryAcc)
acc.get().then(accInfo => {
const vet = accInfo.balance / 1e18 // +" VET"
return vet
})
}
I then call it in flutter with
var a = js.context.callMethod("checkBalance",
["0x70aE85A2fF6030366F512DbcD60Be3828139b498"]);
The problem is (as far as i can tell) that i cant create the Connex Object ("Could not find name 'Connex'. Did you mean 'connex'?ts(2570)" if i hover over Connex)
I have included connex in index.html like this:
<script src="https://unpkg.com/#vechain/connex#2" ></script>
Why does that not work?

Not Populating list in HTML with Javascript

I am learning Javascript. I am working on reading RSS feeds for a personal project. I am using 'RSS-parser' npm library to avoid CORS error.
And also I am using Browserify bundler to make it work on the browser.
When I run this code on the terminal it gives me output without any issue. But when I try with the browser it prints nothing.
My knowledge about Asynchronous JS is limited but I am pretty sure it doesn't have errors in here as I added code to it without changing existing code.
let Parser = require('rss-parser');
let parser = new Parser();
let feed;
async () => {
feed = await parser.parseURL('https://www.reddit.com/.rss');
feedTheList();
};
// setTimeout(function() {
// //your code to be executed after 1 second
// feedTheList();
// }, 5000);
function feedTheList()
{
document.body.innerHTML = "<h1>Total Feeds: " + feed.items.length + "</h1>";
let u_list = document.getElementById("list")[0];
feed.items.forEach(item => {
var listItem = document.createElement("li");
//Add the item text
var newText = document.createTextNode(item.title);
listItem.appendChild(newText);
listItem.innerHTML =item.title;
//Add listItem to the listElement
u_list.appendChild(listItem);
});
}
Here is my HTML code.
<body>
<ul id="list"></ul>
<script src="bundle.js"></script>
</body>
Any guidance is much appreciated.
document.getElementById() returns a single element, not a collection, so you don't need to index it. So this:
let u_list = document.getElementById("list")[0];
sets u_list to `undefined, and you should be getting errors later in the code. It should just be:
let u_list = document.getElementById("list");
Also, when you do:
listItem.innerHTML =item.title;
it will replace the text node that you appended on the previous line with this HTML. Either append the text node or assign to innerHTML (or more correctly, innerText), you don't need to do both.
Looks like the async call is not being executed; You need to wrap it
in an anonymous function call:
See the example here:
https://www.npmjs.com/package/rss-parser
Essentially,
var feed; // change let to var, so feed can be used inside the function
// wrap the below into a function call
(async () => {
feed = await parser.parseURL('https://www.reddit.com/.rss');
feedTheList();
})(); // the (); at the end executes the promise
Now it will execute and feed should have items.
CORS errors when making request
As noted in the documentation at https://www.npmjs.com/package/rss-parser, if you get CORS error on a resource, use a CORS proxy. I've updated their example to fit your code:
// Note: some RSS feeds can't be loaded in the browser due to CORS security.
// To get around this, you can use a proxy.
const CORS_PROXY = "https://cors-anywhere.herokuapp.com/"
let parser = new RSSParser();
(async () => {
await parser.parseURL(CORS_PROXY + 'https://www.reddit.com/.rss', function(err, feed) {
feedTheList(feed);
});
})();
function feedTheList(feed)
{
// unchanged
}
One last thing:
The line
document.body.innerHTML = "<h1>Total Feeds: " + feed.items.length + "</h1>";
Will remove all of the content of <body>
I suggest to look into how element.appendChild works, or just place the <h1> tag in your HTML and modify its innerHTML property instead.

Model return values from another file not working with Sequelize.js

I have the following code that does not work currently.
var config = require('./libs/sequelize-lib.js');
var connection = config.getSequelizeConnection();//Choosing to not pass in variable this time since this should only run via script.
var models = config.setModels(connection);//Creates live references to the models.
//Alter table as needed but do NOT force the change. If an error occurs we will fix manually.
connection.sync({ alter: true, force: false }).then(function() {
models.users.create({
name: 'joe',
loggedIn: true
}).then( task => {
console.log("saved user!!!!!");
});
process.exit();//close the nodeJS Script
}).catch(function(error) {
console.log(error);
});
sequelize-lib.js
var Sequelize = require('sequelize');
exports.getSequelizeConnection = function(stage){
var argv = require('minimist')(process.argv.slice(2)); //If this file is being used in a script, this will attempt to get information from the argument stage passed if it exists
//Change connection settings based on stage variable. Assume localhost by default.
var dbname = argv['stage'] ? argv['stage']+"_db" : 'localdb';
var dbuser = argv['stage'] ? process.env.RDS_USERNAME : 'admin';
var dbpass = argv['stage'] ? process.env.RDS_PASSWORD : 'local123';
var dbhost = argv['stage'] ? "database-"+argv['stage']+".whatever.com" : 'localhost';
//If state variable used during require overide any arguments passed.
if(stage){
dbname = stage+"_db";
dbuser = process.env.RDS_USERNAME
dbpass = process.env.RDS_PASSWORD
dbhost = "database-"+stage+".whatever.com"
}
var connection = new Sequelize(dbname,dbuser,dbpass, {
dialect: 'mysql',
operatorsAliases: false, //This gets rid of a sequelize deprecated warning , refer https://github.com/sequelize/sequelize/issues/8417
host: dbhost
});
return connection;
}
exports.setModels = function(connection){
//Import all the known models for the project.
const fs = require('fs');
const dir = __dirname+'/../models';
var models = {}; //empty model object for adding model instances in file loop below.
//#JA - Wait until this function finishes ~ hence readdirSync vs regular readdir which is async
fs.readdirSync(dir).forEach(file => {
console.log(file);
//Split the .js part of the filename
var arr = file.split(".");
var name = arr[0].toLowerCase();
//Create a modle object using the filename as the reference without the .js pointing to a created sequelize instance of the file.
models[name] = connection.import(__dirname + "/../models/"+file);
})
//Showcase the final model.
console.log(models);
return models; //This returns a model with reference to the sequelize models
}
I can't get the create command to work however with this setup. My guess is the variables must not be passing through correctly somehow. I'm not sure what I'm doing wrong?
The create command definitely works because if in the sequelize-lib.js I modify the setModels function to this...
exports.setModels = function(connection){
//Import all the known models for the project.
const fs = require('fs');
const dir = __dirname+'/../models';
var models = {}; //empty model object for adding model instances in file loop below.
//#JA - Wait until this function finishes ~ hence readdirSync vs regular readdir which is async
fs.readdirSync(dir).forEach(file => {
console.log(file);
//Split the .js part of the filename
var arr = file.split(".");
var name = arr[0].toLowerCase();
//Create a modle object using the filename as the reference without the .js pointing to a created sequelize instance of the file.
models[name] = connection.import(__dirname + "/../models/"+file);
models[name].create({
"name":"joe",
"loggedIn":true
});
})
//Showcase the final model.
console.log(models);
return models; //This returns a model with reference to the sequelize models
}
Then it works and I see the item added to the database! (refer to proof image below)
Take note, I am simply running create on the variable at this point. What am I doing wrong where the model object is not passing between files correctly? Weird part is I don't get any errors thrown in the main file?? It's as if everything is defined but empty or something and the command is never run and nothing added to the database.
I tried this in the main file also and no luck.
models["users"].create({
name: 'joe',
loggedIn: true
}).then( task => {
console.log("saved user!!!!!");
});
The purpose of this all is to read models automatically from the model directory and create instances that are ready to go for every model, even if new one's are added in the future.
UPDATE::
So I did another test that was interesting, it seems that the create function won't work in the .then() function of the sync command. It looks like it was passing it correctly though. After changing the front page to this...
var config = require('./libs/sequelize-lib.js');
var connection = config.getSequelizeConnection();//Choosing to not pass in variable this time since this should only run via script.
var models = config.setModels(connection);//Creates live references to the models using connection previosly created.
models["users"].create({
"name":"joe",
"loggedIn":true
});
//Alter table as needed but do NOT force the change. If an error occurs we will fix manually.
connection.sync({ alter: true, force: false }).then(function() {
process.exit();//close the nodeJS Script
}).catch(function(error) {
console.log(error);
});
Doing this seems to get create to work. I'm not sure if this is good form or not though since the database might not be created at this point? I need a way to get it to work in the sync function.
Well I answered my question finally, but I'm not sure I like the answer.
var config = require('./libs/sequelize-lib.js');
var connection = config.getSequelizeConnection();//Choosing to not pass in variable this time since this should only run via script.
var models = config.setModels(connection);//Creates live references to the models using connection previosly created.
//Alter table as needed but do NOT force the change. If an error occurs we will fix manually.
connection.sync({ alter: false, force: false }).then( () => {
models["users"].create({
"name":"joe",
"loggedIn":true
}).then( user => {
console.log("finished, with user.name="+user.name);
process.exit();
}).catch( error => {
console.log("Error Occured");
console.log(error);
});
}).catch(function(error) {
console.log(error);
});
turns out that process.exit was triggering before create would occur because create happens async. This means that all my code will have to constantly be running through callbacks...which seems like a nightmare a bit. I wonder if there is a better way?

Creating a .txt error output file in protractor made manually not console errors

Hello guys I'm kinda new to js and protractor and I just found out it can't create and modify files, so the question I want to ask is:
Is it possible to manually write test cases logic fails to a text file for example:
I know the code is not correct but you will get the idea i know about jasmine-reporters and with xml file output but it just prints console errors i want one that is custom liek the one below
describe('File output test', function() {
it('should have a title', function() {
browser.ignoreSynchronization=true;
browser.get('https://www.google.com');
});
it('Tests output file',function(){
var searchText = $('#lst-ib');
searchText.sendKeys('Testt')
searchText.sendKeys(protractor.Key.ENTER);
browser.sleep(3000);
if(browser.getTitle() != 'Test')
{
var txtFile = "C:\Users\y\Desktop\test.txt";
var file = new File(txtFile);
var url = browser.getCurrentUrl();
file.open("w");
file.writeln("Error at " + url);
file.close();
}
});
});
conf file pretty basic:
exports.config = {
framework: 'jasmine',
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: ['spec.js']
}
So I simply want to check for the given title at the moment and if it is different from the expected one i want to save the url in an output file so when the test ends i can check afterwards where exactly did something i didnt want happened. I hope I am not talking nonsense
Protractor runs in Node.js environment. So everything, that Node.js has, is available to you. Such as "fs" module. So you can manually save file every time, or (as a better option), write custom Jasmine reporter. Your reporter would expose some variable or function in global namespace to register custom errors and write them into a file after test execution.
Nevermind i found the answer to my question here is my sample code i used to test it
var fs = require('fs-extra')
var file = 'C:/Users/y/Desktop/test/New folder/output.txt'
var counter = 1;
describe('File output test', function() {
it('should have a title', function() {
browser.ignoreSynchronization=true;
browser.get('https://www.facebook.com');
});
it('Tests output file',function(){
email = 'dame#hotmail.com';
pass = 'test123'
var enterMail = $('#email');
enterMail.sendKeys(email);
var enterPass = $('#pass');
enterPass.sendKeys(pass);
enterPass.sendKeys(protractor.Key.ENTER);
browser.sleep(3000);
if(browser.getTitle() != 'Facebook'){
fs.appendFile(file,counter +'. ' + 'Error at login using: ('+email +') as email and ('+pass+') as password.' + "\n" , function (err) {
console.log(err) // => null
})
counter+=1;
}
});
});
I found a module fs-extra which allowed to create and edit some files or documents and i managed to create and write my manual output in a file here is the link to fs-extra https://github.com/jprichardson/node-fs-extra#mkdirsdir-callback in case someone needs it cheers

MongoDB JavaScript Yield large set of results

I'm trying to query a large set of results from a MongoDB over Python. I do this via JavaScript, because I want to get something like the grandchildren in a tree-like structure. My code looks like the following:
col = db.getCollection(...)
var res = new Array();
col.find( { "type" : ["example"] } ).forEach(
function(entry)
{
v1 = col.find( {"_id" : entry["..."]} )
... (walk through the structure) ...
vn = ...
res.push([v1["_id"], vn["data"]]);
}
);
return res;
Now, I'm having the problem, that the resulting array becomes very (too) large and the memory gets exceeded. Is there a way, to yield the results instead of pushing them into an array?
Alright, I think I know, what you mean. I created a structure like the following:
var bulksize = 1000;
var col = db.getCollection("..");
var queryRes = col.find( { ... } )
process = function(entity) { ... }
nextEntries = function()
{
var res = new Array();
for(var i=0; i<bulksize; i++)
{
if(hasNext())
res.push(process(queryRes.next()));
else
break;
}
return res;
}
hasNext = function()
{
return queryRes.hasNext();
}
The script separates the results into bulks of 1000 entries. And from Python side eval the noted script and then I do the following:
while database.eval('hasNext()'):
print "test"
for res in database.eval('return nextEntries()'):
doSth(res)
The interesting thing is, that the console always says:
test
test
test
test
test
test
Then I get the error:
pymongo.errors.OperationFailure: command SON([('$eval', Code('return nextEntries()', {})), ('args', ())]) failed: invoke failed: JS Error: ReferenceError: nextEntries is not defined nofile_a:0
This means, that the first calls of nextEntries() work, but then the function is not there, anymore. Could it be, that MongoDB does something like a clearing of the JavaScript cache? The problem does not depend on the bulksize (tested with 10, 100, 1000, 10000 and always the same result).
Alright, I found a line in the source code of MongoDB, which clears all JavaScripts that are used more than 10 times. So if no changes on the database server are wanted, it is necessary to query the database multiple times and send bulks to the client by selecting amounts of items with help of the skip() and limit() functions. This works surprisingly fast. Thanks for your help.

Categories

Resources