Writing json string into file using Windows Script Host - javascript

I am trying to write json string that I stringified using https://github.com/douglascrockford/JSON-js/blob/master/json2.js ( JSON.stringify) ,
I am trying to save the string and I am getting an error:
Microsoft JScript Runtime Error: Invalid procedure call or argument
at
var textStream = fileObj.OpenAsTextStream(ForWriting, TristateFalse);
this is my code :
var pref = JSON.parse(textPref);
textPref = JSON.stringify(pref);
WSH.echo(textPref)
// Create the new file.
fso.CreateTextFile("d:\\Preferences_temp", true);
var fileObj = fso.GetFile("d:\\Preferences_temp");
var textStream = fileObj.OpenAsTextStream(ForWriting, TristateFalse); <- Microsoft JScript Runtime Error: Invalid procedure call or argument
textStream.Write(textPref);
textStream.Close();

The constants you pass to the FSO methods are not exposed via late binding with new ActiveXObject so you need to define them independently;
var ForWriting = 2;
var TristateFalse = 0;
Edit
var ForWriting = 2;
var TristateTrue = -1;
var textPref = '{"xxx": "AA \u05D5 BB"}';
var pref = JSON.parse(textPref);
textPref = JSON.stringify(pref)
// Create the new file.
var fso = new ActiveXObject("Scripting.FileSystemObject");
//create as unicode
fso.CreateTextFile("c:\\null\\Preferences_temp", true, true);
var fileObj = fso.GetFile("c:\\null\\Preferences_temp");
//open for unicode
var textStream = fileObj.OpenAsTextStream(ForWriting, TristateTrue);
textStream.Write(textPref);
textStream.Close();

Related

Why do I get this error : Malformed UTF-8 data

const license = fs.readFileSync('./license').toString();
var bytes = CryptoJS.AES.decrypt(license, 'mysecretkey123');
var originalText = bytes.toString(CryptoJS.enc.Utf8);
Last line throws an error : Malformed UTF-8 data
It works without error when I run this code in my Electron app before packaging it, but once its packaged in a exe file it throws an error here
The ./license file was created this way :
var licensedata = {license:licen.license, lastpayment:data.lastpayment, macAddress:getmac.default()};
var stringtoencrypt = JSON.stringify(licensedata);
var ciphertext = CryptoJS.AES.encrypt(stringtoencrypt, 'f8LNLIHdb9CT4KYTBF6Az9sNR2r1bMlUjqgCia0teIrg0lZ4iZ7sUSBt7cJqmYE3GrHe082eD9ajIry2');
var cptext = ciphertext.toString();
var fp = "./license";
var encdata = new Uint8Array(Buffer.from(cptext));
fs.writeFileSync(fp, encdata);

File is not defined in JavaScript

I'm writing a code in JavaScript the opens a file then read it:
var txtFile = "/dataset/happy.txt";
var fileH = new File(txtFile);
var fileS = new File("/dataset/sad.txt");
var fileA = new File("/dataset/angry.txt");
var fileSC = new File("/dataset/scared.txt");
var fileSU = new File("/dataset/suprised.txt");
fileH.open("r"); // open file with read access
But I get (ReferenceError: File is not defined) error
What's the problem?
Thank you :)

Protractor excel4node doesn't work

I'm trying to save some data into my excel:
var xl = require('excel4node');
var wb = new xl.Workbook();
var ws = wb.addWorksheet('abc1');
ws.cell(1,1).string('abc2');
ws.cell(1,2).string('abc3');
ws.cell(1,3).string('abc4');
ws.cell(1,4).string('abc5');
It works fine but when i am trying to:
var a = element(by.className('token')).getText();
ws.cell(2,8).string(a);
I get an error:
Failed: val.match is not a function
I know that "a" return a good string value, because I've checked the logs.

Convert binary file to JavaScript string and then to Uint8Array

I'm trying to create a web application that can be used via a file:// URI. This means that I can't use AJAX to load binary files (without turning off security features in the browser, which I don't want to do as a matter of principle).
The application uses a SQLite database. I want to provide the database to a sql.js constructor, which requires it in Uint8Array format.
Since I can't use AJAX to load the database file, I could instead load it with <input type="file"> and FileReader.prototype.readAsArrayBuffer and convert the ArrayBuffer to a Uint8Array. And that's working with the following code:
input.addEventListener('change', function (changeEvent) {
var file = changeEvent.currentTarget.files[0];
var reader = new FileReader();
reader.addEventListener('load', function (loadEvent) {
var buffer = loadEvent.target.result;
var uint8Array = new Uint8Array(buffer);
var db = new sql.Database(uint8Array);
});
reader.readAsArrayBuffer(file);
});
However, <input type="file"> requires user interaction, which is tedious.
I thought I might be able to work around the no-AJAX limitation by using a build tool to convert my database file to a JavaScript object / string and generate a ".js" file providing the file contents, and then convert the file contents to a Uint8Array, somehow.
Psuedocode:
// In Node.js:
var fs = require('fs');
var sqliteDb = fs.readFileSync('path/to/sqlite.db');
var string = convertBufferToJsStringSomehow(sqliteDb);
fs.writeFileSync('build/db.js', 'var dbString = "' + string + '";');
// In the browser (assume "build/db.js" has been loaded via a <script> tag):
var uint8Array = convertStringToUint8ArraySomehow(dbString);
var db = new sql.Database(uint8Array);
In Node.js, I've tried the following:
var TextEncoder = require('text-encoding').TextEncoder;
var TextDecoder = require('text-encoding').TextEncoder;
var sql = require('sql.js');
var string = new TextDecoder('utf-8').decode(fs.readFileSync('path/to/sqlite.db'));
// At this point, I would write `string` to a ".js" file, but for
// the sake of determining if converting back to a Uint8Array
// would work, I'll continue in Node.js...
var uint8array = new TextEncoder().encode(string);
var db = new sql.Database(uint8array);
db.exec('SELECT * FROM tablename');
But when I do that, I get the error "Error: database disk image is malformed".
What am I doing wrong? Is this even possible? The database disk image isn't "malformed" when I load the same file via FileReader.
Using the following code, I was able to transfer the database file's contents to the browser:
// In Node.js:
var fs = require('fs');
var base64 = fs.readFileSync('path/to/sqlite.db', 'base64');
fs.writeFileSync('build/db.js', 'var dbString = "' + base64 + '";');
// In the browser (assume "build/db.js" has been loaded via a <script> tag):
function base64ToUint8Array (string) {
var raw = atob(string);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for (var i = 0; i < rawLength; i += 1) {
array[i] = raw.charCodeAt(i);
}
return array;
}
var db = new sql.Database(base64ToUint8Array(dbString));
console.log(db.exec('SELECT * FROM tablename'));
And that's working with the following code:
input.addEventListener('change', function (changeEvent) {
var file = changeEvent.currentTarget.files[0];
var reader = new FileReader();
reader.addEventListener('load', function (loadEvent) {
var buffer = loadEvent.target.result;
var uint8Array = new Uint8Array(buffer);
var db = new sql.Database(uint8Array);
});
reader.readAsArrayBuffer(file);
});
However, <input type="file"> requires user interaction, which is
tedious.
Using current working approach would be less tedious than attempting to create workarounds. If user intends to use application, user can select file from their filesystem to run application.

JScript to Javascript Conversion

The code below is a web service call to ICEPortal which is in JScript.NET format. Currently Iceportal doesn't have a webservice call using javascript. Has anybody done this using javascript? I need your help to convert the code below to javascript format.
// JScript.NET
var h:ICEPortal.ICEWebService = new ICEPortal.ICEWebService();
var myHeader:ICEPortal.ICEAuthHeader = new ICEPortal.ICEAuthHeader();
myHeader.Username = "distrib#distrib.com";
myHeader.Password = "password";
h.ICEAuthHeaderValue = myHeader;
var brochure:ICEPortal.Brochure;
var ErrorMsg;
var result = h.GetBrochure("MyMappedID", ErrorMsg, brochure);
I think you just need to remove the type definitions (in bold below):
var myHeader :ICEPortal.ICEAuthHeader = new ICEPortal.ICEAuthHeader();)
No idea what the ICEPortal classes are, but if they are available to your Javascript in the global namespace, the following should work. I've added these stubs in for the ICEPortal to test and it works fine for me in Chrome.
You'll obviously want to remove the stubs.
// stubbing out ICEPortal(s)
ICEPortal = {};
ICEPortal.ICEWebService = function() { return true; };
ICEPortal.ICEAuthHeader = function() { return true; };
ICEPortal.ICEWebService.prototype.GetBrochure = function() { return true; };
// end stubbing ICEPortal(s)
var h = new ICEPortal.ICEWebService();
var myHeader = new ICEPortal.ICEAuthHeader();
myHeader.Username = "distrib#distrib.com";
myHeader.Password = "password";
h.ICEAuthHeaderValue = myHeader;
var brochure;
var ErrorMsg;
var result = h.GetBrochure("MyMappedID", ErrorMsg, brochure);

Categories

Resources