Using sql.js in an Electron application - javascript

I am new to Electron. It's pure awesome, and getting started is super fun and easy. For some time now I have been trying to find a "database" solution to use in my application. Of course there is the Web SQL/local storage options, but I am trying to use SQLite. I found sql.js, which is great and easy to use. I could get everything to run correctly put I cannot save/update the database file!
Here is the code:
var remote = require('remote'),
fileSystem = remote.require('fs'),
sql = remote.require('./nodeModules/sql.js'),
database = new sql.Database(fileSystem.readFileSync('./database.sqlite'));
database.run('CREATE TABLE IF NOT EXISTS products (ID integer primary key autoincrement, name text, price integer, stock integer)');
// Save the data back to the file
var data = database.export();
var buffer = new Buffer(data);
fileSystem.writeFileSync("./database.sqlite", buffer);
But I am getting this error from "Buffer": Uncaught TypeError: must start with number, buffer, array or string. Have you run across this issue before ?

I was unable to reproduce this issue on node v6.2.2 (npm v3.9.4) on Windows 10 and OS X 10.11.5. The code is nearly identical to yours:
fs.writeFileSync("filename.sqlite", new Buffer(db.export()));
Check out this repo for more information:
https://github.com/codewisdom/electron-sqljs

I believe you have to read and write the database to the folder returned by calling:
electron.app.getPath('userData')
I created an example project showing how to use sql.js in Electron.

Related

How to read and write to a file (Javascript) in ui automation?

I want to identify few properties during my run and form a json object which I would like to write to a ".json"file and save it on the disk.
var target = UIATarget.localTarget();
var properties = new Object();
var jsonObjectToRecord = {"properties":properties}
jsonObjectToRecord.properties.name = "My App"
UIALogger.logMessage("Pretty Print TEST Log"+jsonObjectToRecord.properties.name);
var str = JSON.stringify(jsonObjectToRecord)
UIALogger.logMessage(str);
// -- CODE TO WRITE THIS JSON TO A FILE AND SAVE ON THE DISK --
I tried :
// Sample code to see if it is possible to write data
// onto some file from my automation script
function WriteToFile()
{
set fso = CreateObject("Scripting.FileSystemObject");
set s = fso.CreateTextFile("/Volumes/DEV/test.txt", True);
s.writeline("HI");
s.writeline("Bye");
s.writeline("-----------------------------");
s.Close();
}
AND
function WriteFile()
{
// Create an instance of StreamWriter to write text to a file.
sw = new StreamWriter("TestFile.txt");
// Add some text to the file.
sw.Write("This is the ");
sw.WriteLine("header for the file.");
sw.WriteLine("-------------------");
// Arbitrary objects can also be written to the file.
sw.Write("The date is: ");
sw.WriteLine(DateTime.Now);
sw.Close();
}
But still unable to read and write data to file from ui automation instruments
Possible Workaround ??
To redirect to the stdout if we can execute a terminal command from my ui automation script. So can we execute a terminal command from the script ?
Haven't Tried :
1. Assuming we can include the library that have those methods and give it a try .
Your assumptions are good, But the XCode UI Automation script is not a full JavaScript.
I don't think you can simply program a normal browser based JavaScript in the XCode UI Automation script.
set fso = CreateObject("Scripting.FileSystemObject");
Is not a JavaScript, it is VBScript which will only work in Microsoft Platforms and testing tools like QTP.
Scripting.FileSystemObject
Is an ActiveX object which only exists in Microsoft Windows
Only few JavaScript functions like basic Math, Array,...etc..Are provided by the Apple JavaScript library, so you are limited to use only the classes provided here https://developer.apple.com/library/ios/documentation/DeveloperTools/Reference/UIAutomationRef/
If you want to do more scripting then Try Selenium IOS Driver http://ios-driver.github.io/ios-driver/
Hey so this is something that I was looking into for a project but never fully got around to implementing so this answer will be more of a guide of what to do than step by step copy and paste.
First you're going to need to create a bash script that writes to a file. This can be as simple as
!/bin/bash
echo $1 >> ${filename.json}
Then you call this from inside your Xcode Instruments UIAutomation tool with
var target = UIATarget.localTarget();
var host = target.host();
var result = host.performTaskWithPathArgumentsTimeout("your/script/path", ["Object description in JSON format"], 5);
Then after your automation ends you can load up the file path on your computer to look at the results.
EDIT: This will enable to write to a file line by line but the actual JSON formatting will be up to you. Looking at some examples I don't think it would be difficult to implement but obviously you'll need to give it some thought at first.

How to create file(.apk) from URL in Jaggery?

I have application store and applications have their url. I want to download apks from those urls to my jaggery server. Although below code(my first solution) create myApp.apk successfully, its not work properly.
First i tried to below code,
var url = "http://img.xxx.com/006/someApp.apk";
var data = get(url, {});
var file = new File("myApp.apk");
file.open("w");
file.write(data.data);
file.close();
when i print data.data value, its look like
i also tried,
var file = new File("http://img.xxx.com/006/someApp.apk");
file.saveAs("myApp.txt");
Can anyone help me?
.apk files are Android application files, and they are expected to start with PK, because they are actually zip archives!
They're not meant to be unzipped, although you can do it to see some of the application resources (but there are better ways for reverse engineering .apk files such as Apktool, if that's what you're looking for).
According to jaggery documentations, file.write is writing the String representation of the object to the file. So that's why you are getting an apk file which cannot be installed.
However you can make it work using copyURLToFile in apache commons-io java library as follows since jaggery supports java itself and all of WSO2 products have apache commons-io library in their class path.
<%
var JFileUtils = Packages.org.apache.commons.io.FileUtils;
var JUrl = Packages.java.net.URL;
var JFile = Packages.java.io.File;
var url = new JUrl("http://img.xxx.com/006/someApp.apk");
JFileUtils.copyURLToFile(url, new JFile("myApp.apk"));
print("done");
%>
Your file will be stored on $CARBON_HOME directory by default, unless you specified relative or absolute path to the file.

Node js / MongoDB replica set array in javascript

Warning: I'm a novice programmer (more of sysadmin). We were given an node js application that's using MongoDB. From what I can tell, the mongo.js file is using mongojs and monq java classes. It was setup with only one MongoDB and I'm trying to setup a new HA environment to use a replica set. Here is what they provided:
var mongojs = require('mongojs');
var monq = require('monq');
var dbName = 'exampledb';
var db = mongojs(dbName, ['collections']);
var client = monq('mongodb://127.0.0.1/exampledb', { w: 1 });
exports.db = db;
exports.ObjectId = mongojs.ObjectId;
exports.monqClient = client;
Now for a replica set, according to this article, I need to make the following change:
var db = mongojs('replset0.com, replset1.com, replset2.com/mydb?slaveOK=true?', ['collections']);
I'm not entirely sure what I need to do for the line after that. I'm guessing I would have to create an array that would contain the host name and port # for each member of the replica set (setup is primary, secondary, arbiter) such as:
var replSet = new replSet();
var replSet[0] = "server0:port0"
var replSet[1] = "server1.:port1"
var replSet[2] = "server2.:port2"
How would I go about detecting which node is the primary? Also if the primary were to fail, I would have to restart the node js application (using forever)?
I found the answer as it's calling MongoDB's URI
http://docs.mongodb.org/manual/reference/connection-string/
Should be something like:
var client = monq('mongodb://server0:port0,server1:port1,server2:port2/[dbname]?replicaSet=[replicaSet Name]
First question: As long as you give it all of the members in the connection string, the mongojs driver should be able to figure out which one is primary. No need to figure it out yourself.
Second question: No, you don't have to restart the node app. The other members in the set will elect a new primary, although it takes time for mongo to detect failure and run the election.
For more information, see the mongodb docs on replica sets.

how to refer SQLite SIMPLE way in Javascript-App just use 'DB_open, execute SQL..' VS2012

I want to write an App (JS) with SQLite (VS2012). So I can't find a easy beginnerguide for this. When I install the SQLite for Windows Runtime. There is a C++ code (GitHub) to insert in the Projekt.
So, what happens with the JS - Projekt?
How can JS refer to properties and methodes of the DB-Objekt (dll, ocx, whatever from the SQLite-Runtime) just to open DB, execute SQL etc. in a simple way?
In Android-Browser following simple JS code (no more) is korrekt:
var shortName = 'testDb';
var version = '1.0';
var displayName = 'test db';
var maxSize = 1048576; // in bytes
mydb = window.openDatabase(shortName, version, displayName, maxSize);
function(transaction) {
transaction.executeSql('CREATE TABLE IF NOT EXISTS person(id INTEGER ..);', [], NullDataHandler, errorHandler);
}
Is somebody here - can show me the same SIMPLE in VS2012 without an Overhead, advanced settings and error-mangement - I can't follow the code?
1. DB_open : ..
2. Execute SQL : ..
Many Greetings from Bavaria
ralphi
PS: Why isn't it allowed to insert links?
I assume your Javascript is running on a web page. Actually, There is no way to manipulate the Sqlite database from a web page. For security reason, the ability to access local files from a web page is strictly limited. Despite new HTML5-supported browsers allow you to access local files in a limited and safe way, directly using local database is not possible in HTML world.

Values for global Javascript variable is wrong at the momemt to get it

I am ready with a port from a php mvc application to asp.net mvc (using a lot of javascript and google maps). The application works quite well on my development machine (Win 7 + IIS 7). But the problems start on production server. for some reason i have a javascript file wich is not working well when i am using it from my production server.
i.e. I have my view where i load all the data from db and and after that I put this on an global variable array called global_sites_am. Each row in the array contains attributes like latitud ,longitud and name.... After that this array is readed from the js file called maps.js.
var position = new google.maps.LatLng(global_sites_am[i].latitud,global_sites_am[i].longitud);
addMarker(position,global_sites_am[i].name,i);
For some reason this piece of code work fine on my development machine but it doesn't when i have installed the app on production server.
I.E. On Development machine : global_sites_am[0].latitud = 45,6789566 and global_sites_am[i].longitud=72,69452015
But on Production machine : global_sites_am[0].latitud = 45 and global_sites_am[i].longitud=72
What i am doing wrong?
Update: Here is How I load the value from the db to the javascript file:
global_sites_am[count]=new Object();
global_sites_am[count].name='<%=site.Name%>';
global_sites_am[count].latitud=<%=site.Latitud%>;
global_sites_am[count].longitud=<%=site.Longitud%>;
This is one of my properties:
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Double Latitud
{
get
{
return _Latitud;
}
set
{
OnLatitudChanging(value);
ReportPropertyChanging("Latitud");
_Latitud = StructuralObject.SetValidValue(value);
ReportPropertyChanged("Latitud");
OnLatitudChanged();
}
}
Some debug info from Chrome: http://oi49.tinypic.com/2j4q7p4.jpg. In the image you will see that the values at the moment to load in the page are correct, but at the moment to read them are wrong.
Finally the problem was solved using the next line on the web.config:
globalization uiCulture="en-US" culture="en-US"

Categories

Resources