Best JavaScript code snippet using wpt
Scoot-0.1.10.js
Source:Scoot-0.1.10.js
1/*2Scoot 3The MIT License (MIT)4Copyright (c) 2016,2017 Edward C. Zeglen III5Permission is hereby granted, free of charge, to any person6obtaining a copy of this software and associated documentation7files (the "Software"), to deal in the Software without8restriction, including without limitation the rights to use,9copy, modify, merge, publish, distribute, sublicense, and/or sell10copies of the Software, and to permit persons to whom the11Software is furnished to do so, subject to the following12conditions:13The above copyright notice and this permission notice shall be14included in all copies or substantial portions of the Software.15THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,16EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES17OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND18NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT19HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,20WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING21FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR22OTHER DEALINGS IN THE SOFTWARE.23*/24(function (window) {25 // You can enable the strict mode commenting the following line 26 // 'use strict';27 // This function will contain all our code28 function ScootLib() {29 var _Scoot = {};30 31 var myversioninfo = {32 "number": "1.0.10",33 "date": "29-DEC-2016"34 };35 _Scoot.versioninfo = function () {36 return myversioninfo;37 }38 // ======================= FILE 39 _Scoot.file = function () {40 this.fso = new ActiveXObject("Scripting.FileSystemObject");41 this.load = function (filespec, into, spliton) {42 var ForReading = 1;43 var f1 = this.fso.OpenTextFile(filespec, ForReading);44 var text = f1.ReadAll();45 f1.close();46 if (arguments.length == 3) {47 var temp = text.split(spliton);48 for (i = 0; i < temp.length; i++) {49 if (temp[i].length > 0)50 into.push(temp[i]);51 }52 }53 return (text);54 }55 this.rename = function (filespec, newfilename) {56 if (this.exists(filespec)) {57 var f1 = this.fso.GetFile(filespec);58 f1.name = newfilename;59 f1 = null;60 }61 }62 this.copy = function (source, destination, overwrite) {63 var _overwrite = true;64 if (arguments.length > 2) {65 _overwrite = overwrite;66 }67 if (this.exists(source)) {68 this.fso.CopyFile(source, destination, _overwrite);69 }70 }71 this.exists = function (filespec) {72 return (this.fso.FileExists(filespec));73 }74 this.delete = function (filespec) {75 if (this.fso.FileExists(filespec)) {76 this.fso.DeleteFile(filespec);77 }78 }79 this.browse = function (startinfolder) {80 //alert("not coded yet.") // find this code we have it somewhere I think? 81 // or do we just use input type-file? i think so.82 }83 this.save = function (filespec, text) {84 var f1 = this.fso.CreateTextFile(filespec, true);85 f1.Write(text);86 f1.close();87 }88 this.shell = function (filespec, cmdargs, windowstyle, waitonreturn) {89 var _windowstyle = 5;90 var _waitonreturn = false;91 92 if (arguments.length > 2) 93 _windowstyle = windowstyle;94 95 if (arguments.length > 3) 96 _waitonreturn = waitonreturn;97 if (this.exists(filespec)) {98 var wShell = new ActiveXObject("wScript.Shell");99 wShell.Run(filespec + ' "' + cmdargs + '"', _windowstyle, _waitonreturn);100 }101 }102 return (this);103 }104 // ======================= FOLDER105 _Scoot.folder = function () {106 this.fso = new ActiveXObject("Scripting.FileSystemObject");107 this.subfolders = null;108 109 this.exists = function (folderspec) {110 return (this.fso.FolderExists(folderspec));111 }112 this.parentfolder = function (folderspec) {113 var path = this.fso.GetParentFolderName(folderspec);114 return (path);115 }116 this.scriptfolder = function () {117 var path = this.fso.GetParentFolderName(document.location);118 var m = path.split("///");119 path = (m[1].replace(/\//g, "\\"));120 return (path);121 }122 this.parentof = function (thisfolderSpec) {123 var fso = this.fso;124 var path = "";125 if (fso.FolderExists(thisfolderSpec)) {126 path = fso.GetParentFolderName(thisfolderSpec);127 }128 return (path);129 }130 this.browse = function (startinfolder, dialogtitle) {131 var returnvalue = null;132 var usedialogtitle = "Please select a folder ...";133 if (dialogtitle != null) { usedialogtitle = dialogtitle; }134 var oShell = new ActiveXObject("Shell.Application");135 var f = oShell.BrowseForFolder(0, usedialogtitle, 0, startinfolder);136 if (f != null) { returnvalue = f.Items().Item().path; }137 return (returnvalue);138 }139 this.open = function (folderspec, into) {140 141 if (this.fso.FolderExists(folderspec)) {142 var oFolder = this.fso.GetFolder(folderspec);143 // Reference the File collection of the Text directory144 var filecollection = oFolder.SubFolders;145 // Traverse through the FileCollection using the FOR loop146 for (var objEnum = new Enumerator(filecollection) ; !objEnum.atEnd() ; objEnum.moveNext()) {147 var strFileSpec = objEnum.item();148 var oSubFolder = this.fso.GetFolder(strFileSpec);149 150 var filename = oSubFolder.name; // this.fso.GetFolderName(strFileSpec)151 var obj = {};152 obj["name"] = filename;153 obj["spec"] = strFileSpec;154 into.push(obj);155 }156 // Destroy and de-reference enumerator object157 delete objEnum;158 objEnum = null;159 // De-reference FileCollection and Folder object160 filecollection = null;161 oFolder = null;162 }163 }164 this.create = function (folderspec) {165 if (this.fso.FolderExists(folderspec)) {166 alert("Folder already exists: " + folderspec);167 } else {168 this.fso.CreateFolder(folderspec);169 }170 171 }172 this.delete = function (folderspec) {173 if (this.fso.FolderExists(folderspec)) {174 this.fso.DeleteFolder(folderspec, true);175 } else {176 alert("Unable to locate and delete folder: " + folderspec);177 }178 }179 this.files = function (folderspec, into) {180 if (this.fso.FolderExists(folderspec)) {181 var oFolder = this.fso.GetFolder(folderspec);182 // Reference the File collection of the Text directory183 var filecollection = oFolder.Files;184 // Traverse through the FileCollection using the FOR loop185 for (var objEnum = new Enumerator(filecollection) ; !objEnum.atEnd() ; objEnum.moveNext()) {186 var strFileSpec = objEnum.item();187 var filename = this.fso.GetFileName(strFileSpec)188 var filex = this.fso.GetFile(strFileSpec);189 var folderx = this.fso.GetParentFolderName(strFileSpec);190 var folder = this.fso.GetFolder(folderx);191 var obj = {};192 obj["name"] = filename;193 obj["spec"] = strFileSpec;194 obj["foldername"] = folder.name;195 obj["mdate"] = new Date(filex.datelastmodified);196 obj["size"] = filex.size;197 into.push(obj);198 }199 // Destroy and de-reference enumerator object200 delete objEnum;201 objEnum = null;202 // De-reference FileCollection and Folder object203 filecollection = null;204 oFolder = null;205 }206 }207 return (this);208 }209 // ======================= XML (DATA)210 _Scoot.XMLConnection = function (datalocation, datasource) {211 // properties212 this.spec = datalocation;213 this.source = datasource;214 this.filespec = this.spec + "\\" + this.source + ".xml";215 this.data = null; // 216 this.DOM = null; // Exposes the Open()ned DOM for direct handling if needed.217 this.open = function (datarootname) {218 if (arguments.length == 0) {219 return;220 }221 var oFS = new ActiveXObject("Scripting.FileSystemObject");222 223 if (oFS.FileExists(this.filespec)) {224 var jsonData = this.loadxml(this.filespec);225 this.data = jsonData[datarootname];226 }227 }228 this.loadxml = function (filespec) {229 var xmlDOM = new ActiveXObject("Microsoft.XMLDOM");230 xmlDOM.load(filespec);231 this.DOM = xmlDOM;232 return (XML2jsobj(xmlDOM));233 }234 this.fromxml = function (xml) {235 var xmlDOM = new ActiveXObject("Microsoft.XMLDOM");236 xmlDOM.async = false;237 xmlDOM.loadXML(xml);238 this.DOM = xmlDOM;239 return (XML2jsobj(xmlDOM));240 }241 /**242 * XML2jsobj v1.0243 * Converts XML to a JavaScript object244 * so it can be handled like a JSON message245 *246 * By Craig Buckler, @craigbuckler, http://optimalworks.net247 *248 * As featured on SitePoint.com:249 * http://www.sitepoint.com/xml-to-javascript-object/250 *251 * Please use as you wish at your own risk.252 */253 function XML2jsobj(node) {254 var data = {};255 // append a value256 function Add(name, value) {257 if (data[name]) {258 if (data[name].constructor != Array) {259 data[name] = [data[name]];260 }261 data[name][data[name].length] = value;262 }263 else {264 data[name] = value;265 }266 };267 // element attributes268 if (node.nodeType == 1) {269 var c, cn;270 for (c = 0; cn = node.attributes[c]; c++) {271 Add(cn.name, cn.value);272 }273 }274 // child elements275 for (c = 0; cn = node.childNodes[c]; c++) {276 if (cn.nodeType == 1) {277 if (cn.childNodes.length == 1 && cn.firstChild.nodeType == 3) {278 // text value279 Add(cn.nodeName, cn.firstChild.nodeValue);280 }281 else {282 // sub-object283 if ((cn.nodeValue == null) && (cn.childNodes.length == 0)) {284 // its a text node with no children. it becomes an emptystring property of the object.285 if (cn.nodeValue == null) {286 Add(cn.nodeName, "");287 } else {288 Add(cn.nodeName, XML2jsobj(cn));289 }290 } else {291 Add(cn.nodeName, XML2jsobj(cn));292 }293 }294 }295 }296 return data;297 }298 }299 // ======================= ADO (DATA)300 _Scoot.ADOConnection = function (dataconnectionstring) {301 this.conn = dataconnectionstring;302 this.data = null;303 this.formats = [304 { "match": new RegExp(/\\/g), "with": "\\\\" },305 { "match": new RegExp(/"/g), "with": "'" }306 ];307 308 function kvpToObject(name, value) {309 if (value == null) {310 return ('"' + name + '":null ');311 }312 return ('"' + name + '":"' + value + '"');313 }314 this.dateforado = function (adate) {315 if (arguments.length > 0)316 var m = adate;317 else318 var m = new Date();319 var dateString = _Scoot.pad(m.getMonth() + 1, '0', 2) + "-" + _Scoot.pad(m.getDate(), '0', 2) + "-" + m.getFullYear();320 return (dateString);321 }322 this.execute = function (sql) {323 try {324 var adoCmd = new ActiveXObject("ADODB.Command");325 adoCmd.ActiveConnection = this.conn;326 adoCmd.CommandText = sql;327 adoCmd.Execute();328 return true;329 } catch (err) {330 alert(err);331 return false;332 }333 }334 this.testconnection = function (connectionstring) {335 var adoCnn = new ActiveXObject("ADODB.Connection");336 try {337 adoCnn.open(connectionstring);338 return true;339 } catch (err) {340 alert(err);341 return false;342 }343 }344 345 function formatField(field, formats) {346 try {347 for (findex = 0; findex < formats.length; findex++) 348 field = field.replace(formats[findex].match, formats[findex].with);349 } catch (err) {350 }351 return (field);352 }353 this.save = function (sql, astype, filespec, timeout) {354 var deftimeout = 30;355 if (arguments.length == 4)356 deftimeout = timeout;357 var adoConn = new ActiveXObject("ADODB.Connection");358 adoConn.CommandTimeout = deftimeout;359 adoConn.Open(this.conn);360 var adoRS = new ActiveXObject("ADODB.RecordSet");361 adoRS.Open(sql, adoConn);362 if (adoRS.EOF != true) {363 var text = '"' + adoRS.GetString(2, -1, '","', '"\r\n"', " ");364 // remove the last " which is on a line by iteself for some reason.365 var final = text.substring(0, text.length - 1);366 Scoot.file().save(filespec, final);367 }368 adoRS.Close;369 }370 this.open = function (sql, into, selector) {371 var bInto = false;372 if (arguments.length > 1) bInto = true;373 var bSelector = false;374 if (arguments.length > 2) bSelector = true;375 var adoRS = new ActiveXObject("ADODB.RecordSet");376 var bFirstObject = true;377 var tablename = "fred";378 var sOut = '{ "' + tablename + '": [';379 adoRS.Open(sql, this.conn);380 381 while (adoRS.EOF != true) {382 var sObject = "{ ";383 for (i = 0; i < adoRS.Fields.Count; i++) {384 // note: SQL Fields of type VARCHAR(MAX) will fail here.385 var fname = formatField(adoRS.Fields(i).Name, this.formats)386 var fvalue = formatField(adoRS.Fields(i).value, this.formats)387 388 if (i > 0)389 sObject += ", " + kvpToObject(fname, fvalue);390 else391 sObject += kvpToObject(fname, fvalue);392 }393 sObject += " } ";394 if (!bFirstObject) {395 sOut += "," + sObject;396 } else {397 sOut += sObject;398 bFirstObject = false;399 }400 adoRS.MoveNext();401 }402 sOut += " ] } ";403 adoRS.Close;404 405 // scoot does not understand a comments field in any sql table!!! EVER 406 // do not include a nullable comments field!!!!! it doesn't work!407 //alert(JSON.stringify(sOut));408 409 this.data = JSON.parse(sOut).fred;410 411 if (into == null) { // nothing here so return whatever value you "selector"ed.412 return (this.data[0][selector]);413 }414 if (bInto) {415 if (into == undefined) { // nothing here, get out416 return;417 }418 if (Array.isArray(into)) { // var x = []419 this.data.forEach(function (item, index) {420 into.push(item);421 if ((bSelector) && (typeof(selector) == 'object')) {422 if (item[selector.key] == selector.value) {423 selector.item = item;424 }425 }426 });427 return;428 } 429 430 switch (typeof (into)) {431 case ('object'): 432 try {433 for (prop in into) {434 into[prop] = this.data[0][prop];435 }436 } catch (err) { // return null on errors437 into[prop] = null438 }439 break;440 case ('function'):441 this.data.forEach(function (item, index) {442 into.push(item);443 if ((bSelector) && (typeof (selector) == 'object')) {444 if (item[selector.key] == selector.value) {445 selector.item = item;446 }447 }448 });449 break;450 default: // self.x = ko.obserableArray([]);451 this.data.forEach(function (item, index) {452 into.push(item);453 if ((bSelector) && (typeof (selector) == 'object')) {454 if (item[selector.key] == selector.value) {455 selector.item = item;456 }457 }458 });459 break;460 }461 }462 }463 }464 // ======================= JSON (DATA)465 _Scoot.JSONConnection = function (datalocation, datasource) {466 // properties467 this.spec = datalocation;468 this.source = datasource;469 this.filespec = this.spec + "\\" + this.source + ".json";470 this.data = null;471 this.mapindex = "";472 // methods473 this.open = function (mapindex, into) {474 try {475 if (arguments.length > 0) {476 // we also have the mapindex477 this.mapindex = mapindex;478 }479 // load the json from the file480 var oFS = new ActiveXObject("Scripting.FileSystemObject");481 482 if (oFS.FileExists(this.filespec)) {483 var fileText = loadfiletext(this.filespec);484 this.data = JSON.parse(fileText);485 if (arguments.length > 1) {486 // we have "into"487 this.data[this.source].forEach(function (item, index) {488 into.push(item);489 });490 }491 return true;492 } else {493 return false;494 }495 } catch (err) {496 return false;497 }498 }499 // methods500 this.update = function (data, asname) {501 // save the data as JSON back to an existing the file502 this.data = data;503 var obj = {};504 if (asname == null)505 obj[this.source] = data;506 else507 obj[asname] = data;508 509 var JSONText = ko.toJSON(obj);510 511 try {512 savefiletext(this.filespec, JSONText);513 return (true);514 }515 catch (err) {516 alert("Error in saving JSON to " + this.filespec + ": " + err);517 return (false);518 }519 }520 // used for saving JSON with indexes to simulate "tables".521 this.updatetable = function (index, data) {522 // save the data as JSON back to an existing the file523 524 var obj = {};525 obj["index"] = index;526 obj[this.source] = data;527 var JSONText = ko.toJSON(obj);528 try {529 savefiletext(this.filespec, JSONText);530 return (true);531 }532 catch (err) {533 alert("Error in saving JSON to " + this.filespec + ": " + err);534 return (false);535 }536 }537 this.add = function (obj) {538 // this assumes your object contains and id property539 var currentindex = this.data["index"] + 1;540 obj[this.mapindex] = currentindex;541 this.data[this.source].push(obj);542 this.UpdateTable(currentindex, this.data[this.source]);543 return (obj.id);544 }545 this.get = function (url, params) {546 // could we do an jQuery ajax get here ??547 }548 this.post = function (url, params, data) {549 // could we do an jQuery ajax post here ??550 }551 // returns an object where the field name = the value provided.552 // query("username", "thisusername") = that user object if its found.553 this.query = function (field, value) {554 var returnvalue = null;555 var ds = this.data[this.source];556 for (i = 0; i < ds.length; i++) {557 var obj = ds[i];558 if (obj[field] == value) {559 returnvalue = obj;560 break; // you break on the first one, but what if you always returned an array? do it.561 }562 }563 return (returnvalue);564 }565 this.narrow = function (field, value) {566 // returns a result set narrowed down by the match on the field = value.567 var returnvalue = [];568 var ds = this.data[this.source];569 for (i = 0; i < ds.length; i++) {570 var obj = ds[i];571 if (obj[field] == value) {572 returnvalue.push(obj);573 }574 }575 return (returnvalue);576 }577 function loadfiletext(filespec) {578 var fso = new ActiveXObject("Scripting.FileSystemObject");579 var ForReading = 1;580 var f1 = fso.OpenTextFile(filespec, ForReading);581 var text = f1.ReadAll();582 f1.close();583 return (text);584 }585 function savefiletext(filespec, text) {586 var fso = new ActiveXObject("Scripting.FileSystemObject");587 var f1 = fso.CreateTextFile(filespec, true);588 f1.Write(text);589 f1.close();590 }591 }592 // ======================= COOKIELESS SESSION ( USED BY .SHARED )593 /*594 Implements cookie-less JavaScript session variables595 v1.0596 597 By Craig Buckler, Optimalworks.net598 As featured on SitePoint.com599 Please use as you wish at your own risk.600 601 Modified by ECZ for scoot.602 Renamed scoot_Session. Removed testing for JSON.603 604 Usage:605 606 // store a session value/object607 Session.set(name, object);608 609 // retreive a session value/object610 Session.get(name);611 612 // clear all session data613 Session.clear();614 615 // dump session data616 Session.dump();617 618 */619 function Session() {620 // window object621 var win = window.top || window;622 // session store623 var store = (win.name ? JSON.parse(win.name) : {});624 // save store on page unload625 function Save() {626 win.name = JSON.stringify(store);627 };628 // page unload event629 if (window.addEventListener) window.addEventListener("unload", Save, false);630 else if (window.attachEvent) window.attachEvent("onunload", Save);631 else window.onunload = Save;632 // public methods633 return {634 // set a session variable635 set: function (name, value) {636 store[name] = value;637 },638 // get a session value639 get: function (name) {640 return (store[name] ? store[name] : undefined);641 },642 // clear session643 clear: function () { store = {}; },644 // dump session data645 dump: function () { return JSON.stringify(store); }646 };647 }648 // ======================= SHARED649 _Scoot.shared = function (spec) {650 this.spec = spec651 this.data = null;652 this.sharedname = "_pages_shared";653 654 this.init = function () {655 if (this.spec == undefined) return;656 if (this.spec == null) return;657 var dc = _Scoot.data("JSON", this.spec, this.sharedname);658 dc.open();659 660 if (dc.data != null) {661 this.data = dc.data[this.sharedname];662 }663 }664 this.update = function (data) {665 if (this.spec == null) return;666 var dc = _Scoot.data("JSON", this.spec, this.sharedname);667 dc.open();668 dc.update(data, this.sharedname);669 }670 this.save = function () {671 this.update(this.data);672 }673 // the shared control inits automatically674 this.init();675 }676 // ======================= DATA677 _Scoot.data = function (type, location, name) {678 switch (type.toUpperCase()) {679 case "JSON":680 return (new _Scoot.JSONConnection(location, name));681 case "XML":682 return (new _Scoot.XMLConnection(location, name));683 case "ADO":684 return (new _Scoot.ADOConnection(location));685 }686 }687 // ======================= PAGE ( OBJECT )688 function PageControl(name, isroot, sharedspec) {689 var self = this;690 var oShared = null;691 // properties692 this.name = name;693 this.spec = null;694 this.isroot = isroot;695 this.config = null;696 this.shared = null;697 this.session = null;698 this.includes = [];699 this.urls = null;700 // methods701 this.init = function (isroot, sharedspec) {702 // it knows where its running from703 this.spec = _Scoot.folder().scriptfolder();704 // a name value pair set based on the pagename.json705 this.config = new _Scoot.JSONConnection(this.spec, this.name);706 this.config.open();707 // uses window.name to set a variable we can track across pages.708 this.session = new Session();709 // we are the root page, setup shared according to default or whereever they want it to be.710 if (isroot != undefined) {711 if (isroot) {712 if (sharedspec != undefined) {713 this.setshared(this.spec + "\\" + sharedspec);714 } else {715 this.setshared(this.spec);716 }717 }718 }719 oShared = new _Scoot.shared(this.getshared());720 }721 this.value = function (name, value) {722 if (arguments.length == 1) {723 return (this.config.data.items[name]);724 } else {725 update(this, name, value);726 }727 }728 this.values = function () {729 return (this.config.data.items);730 }731 this.setshared = function (spec) {732 this.session.set("sharedspec", spec);733 }734 this.getshared = function () {735 return (this.session.get("sharedspec"));736 }737 this.shared = function (name, value) {738 if (arguments.length == 0) return oShared;739 if (arguments.length == 1) {740 return (oShared.data[name]);741 } else {742 oShared.data[name] = value;743 }744 }745 // methods746 this.parentfolder = function () {747 return (_Scoot.folder().parentfolder(this.spec));748 }749 function update(page, configitemname, configitemvalue) { // private750 // updating a page config value.751 var obj = page.config.data.items;752 if (configitemvalue == null)753 delete obj[configitemname];754 else755 obj[configitemname] = configitemvalue;756 page.config.update(obj, "items");757 // you must do this for some reason.758 page.config.open();759 }760 this.include = function (url, id) {761 var obj = { "url": url, "id": id };762 this.includes.push(obj);763 }764 function seturl(obj) {765 return $.get(obj.url, function (data) {766 $(obj.id).html(data);767 });768 }769 this.load = function (runafterincludesload) {770 if (this.includes.length == 0) return;771 this.urls = this.includes.map(function (obj) {772 return seturl(obj);773 });774 var tt = $.when.apply(this, this.urls);775 var xx = tt.done(function () {776 runafterincludesload();777 });778 }779 // the page control inits automatically780 this.init(isroot, sharedspec);781 }782 // ======================= PAGE783 _Scoot.page = function (name, isroot, sharedspec) {784 return (new PageControl(name, isroot, sharedspec));785 }786 787 // ======================= INCLUDED STRING FUNCTIONS 788 _Scoot.pad = function (text, char, length, direction) {789 var paddingDirection = "left";790 if (arguments.length > 3) {791 // we have direction792 paddingDirection = direction.toLowerCase();793 }794 if (paddingDirection.toLowerCase() == "left") {795 var s = new String(text);796 while (s.length < length) s = char + s;797 return (s);798 } else {799 var s = new String(text);800 while (s.length < length) s = s + char;801 return (s);802 }803 }804 _Scoot.left = function (str, n) {805 if (n <= 0)806 return "";807 else if (n > String(str).length)808 return str;809 else810 return String(str).substring(0, n);811 }812 _Scoot.right = function (str, n) {813 if (n <= 0)814 return "";815 else if (n > String(str).length)816 return str;817 else {818 var iLen = String(str).length;819 return String(str).substring(iLen, iLen - n);820 }821 }822 // ======================= END823 824 return _Scoot;825 }826 // We need that our library is globally accesible, then we save in the window827 if (typeof (window.Scoot) === 'undefined') {828 window.Scoot = ScootLib();829 }...
filesystem.js
Source:filesystem.js
1const ADODB = require('ADODB.Stream')2const FSO = require('Scripting.FileSystemObject')3const { security, allow } = require('argv')4const { ByteToHex, HexToByte, Uint8ToHex } = require('hex')5const { Enumerator } = require('JScript')6const { toWin32Sep, split, absolute, relative, CurrentDirectory: cwd, resolve } = require('pathname')7const { Type } = require('VBScript')8const chardet = require('chardet')9const genGUID = require('genGUID')10const http = require('Msxml2.XMLHTTP')1112const { NONE, _FUNCTION } = require('text')13const VB_BYTE = 'vbByte[]'14const AD_TYPE_BINARY = 115const AD_TYPE_TEXT = 216const AD_SAVE_CREATE_OVER_WRITE = 217const UTF_8 = 'UTF-8'18const UTF_8BOM = 'UTF-8BOM'19const UTF_8N = 'UTF-8N'2021const readFileSync = function filesystem_readFileSync(filespec, encode) {22 // (filespec: string, encode?: string): string2324 if (encode == null) return new Buffer(readByteFileSync(filespec))25 return readTextFileSync(filespec, encode)26}2728const readTextFileSync = function filesystem_readTextFileSync(filespec, encode) {29 // (filespec: string, encode?: string): string3031 let byte = readByteFileSync(filespec)32 if (byte === null) return NONE33 let buffer = new Buffer(byte)34 let encoding = null35 if (buffer.length >= 3) encoding = encode != null ? encode : chardet.detect(buffer)36 else encoding = UTF_837 if (encoding.toUpperCase().startsWith(UTF_8)) {38 encoding = UTF_839 }40 if (encoding === UTF_8 && buffer[0] === 0xef && buffer[1] === 0xbb && buffer[2] === 0xbf) {41 byte = HexToByte(ByteToHex(byte).replace(/^efbbbf/, NONE))42 }43 return ByteToText(byte, encoding)44}4546const writeFileSync = function filesystem_writeFileSync(filespec, data, encode) {47 // (filespec: string, data: Buffer|byte|string, encode?: string): string4849 if (data instanceof Buffer) data = data.toByte()50 if (Type(data) === VB_BYTE) {51 try {52 ADODB.Open()53 ADODB.Type = AD_TYPE_BINARY54 ADODB.Position = 055 ADODB.SetEOS()56 ADODB.Write(data)57 ADODB.SaveToFile(filespec, AD_SAVE_CREATE_OVER_WRITE)58 ADODB.Close()59 return `Save operation succeeded '${filespec}'`60 } catch (error) {61 error.message += `\nSave operation failed. filespec: ${filespec}`62 throw error63 }64 }65 return writeTextFileSync(filespec, data, encode)66}6768const writeTextFileSync = function filesystem_writeTextFileSync(filespec, text, encode) {69 // (filespec: string, text: string, encode?: string): string7071 let spliBbom = false72 try {73 ADODB.Open()74 ADODB.Type = AD_TYPE_TEXT75 ADODB.Position = 076 ADODB.SetEOS()77 if (encode != null) {78 const _enc = encode.toUpperCase()79 if (_enc.startsWith(UTF_8)) ADODB.CharSet = UTF_880 else ADODB.CharSet = encode81 if (_enc === UTF_8BOM) spliBbom = false82 else if (_enc === UTF_8N) spliBbom = true83 else spliBbom = true84 }85 ADODB.WriteText(text)86 if (spliBbom) {87 ADODB.Position = 088 ADODB.Type = AD_TYPE_BINARY89 ADODB.Position = 390 let bytes = ADODB.Read()91 ADODB.Position = 092 ADODB.SetEOS()93 ADODB.Write(bytes)94 }95 ADODB.SaveToFile(filespec, AD_SAVE_CREATE_OVER_WRITE)96 return `Save operation succeeded. '${filespec}'`97 } catch (error) {98 error.message += `\nSave operation failed. filespec: ${filespec}`99 return error100 } finally {101 ADODB.Close()102 }103}104105// util106const readByteFileSync = function filesystem_readByteFileSync(filespec) {107 // (filespec: string): byte108109 let byte = NONE110 try {111 ADODB.Open()112 ADODB.Type = AD_TYPE_BINARY113 ADODB.Position = 0114 ADODB.SetEOS()115 ADODB.LoadFromFile(filespec)116 byte = ADODB.Read()117 } catch (error) {118 error.message += `\n (readByteFileSync filespec: ${filespec})`119 throw error120 } finally {121 ADODB.Close()122 }123 return byte124}125126const ByteToText = function filesystem_ByteToText(byte, encode) {127 // (byte: byte, encode?: string): string128129 try {130 ADODB.Open()131 ADODB.Type = AD_TYPE_BINARY132 ADODB.Position = 0133 ADODB.SetEOS()134 ADODB.Write(byte)135 ADODB.Position = 0136 ADODB.Type = AD_TYPE_TEXT137 if (encode != null) ADODB.Charset = encode138 return ADODB.ReadText()139 } catch (error) {140 error.message += `\n (ByteToText encode: ${encode})`141 throw error142 } finally {143 ADODB.Close()144 }145}146147const BufferToText = function filesystem_BufferToText(buff, encode) {148 // (buff: Buffer, encode?: string): string149150 if (!(buff instanceof Buffer)) throw new Error('A parameter other than a buffer is passed as an argument')151 if (buff.length === 0) return NONE152 const byte = HexToByte(Uint8ToHex(buff))153 return ByteToText(byte, encode || chardet.detect(buff))154}155156const existsFileSync = function filesystem_existsFileSync(filespec) {157 // (filespec: string): bool158159 return FSO.FileExists(toWin32Sep(filespec))160}161162const existsdirSync = function filesystem_existsdirSync(dirspec) {163 // (dirspec: string): bool164165 return FSO.FolderExists(toWin32Sep(dirspec))166}167168const existsSync = function filesystem_existsSync(filespec) {169 // (filespec: string): bool170171 if (existsFileSync(filespec)) return 'file'172 if (existsdirSync(filespec)) return 'directory'173 return false174}175176const exists = function filesystem_exists(filespec, callback) {177 // (filespec: string, callback: function): bool178179 const res = existsSync(filespec)180 return callback == null ? res : callback(res)181}182183const copyFileSync = function filesystem_copyFileSync(from, to, overwrite) {184 // (from: string, to: string): string185186 FSO.CopyFile(from, to, overwrite)187 return `copyFileSync operation succeeded. '${from}' => '${to}'`188}189190const moveFileSync = function filesystem_moveFileSync(from, to) {191 // (from: string, to: string): string192193 FSO.MoveFile(from, to)194 return `moveFileSync operation succeeded. '${from}' => '${to}'`195}196197const mergeFileSync = function filesystem_mergeFileSync(src, dest) {198 // (src: string[], dest: string): string199200 try {201 ADODB.Open()202 ADODB.Type = AD_TYPE_BINARY203 ADODB.Position = 0204 ADODB.SetEOS()205206 src.map((spec) => {207 ADODB.LoadFromFile(spec)208 const bytes = ADODB.Read()209 ADODB.Position = 0210 ADODB.SetEOS()211 return bytes212 }).forEach((bytes) => {213 ADODB.Write(bytes)214 ADODB.Position = ADODB.Size215 })216217 ADODB.SaveToFile(dest, AD_SAVE_CREATE_OVER_WRITE)218219 return `mergeFileSync operation succeeded. '${dest}'`220 } catch (error) {221 throw error222 } finally {223 ADODB.Close()224 }225}226227const deleteFileSync = function filesystem_deleteFileSync(filespec) {228 // (filespec: string): string229230 if (FSO.FileExists(filespec)) {231 FSO.DeleteFile(filespec)232 return `deleteFileSync operation succeeded. '${filespec}'`233 }234 return `deleteFileSync operation failed. '${filespec}'`235}236237const mkdirSync = function filesystem_mkdirSync(dirspec) {238 // (dirspec: string): string]239240 if (!FSO.FolderExists(dirspec)) {241 FSO.CreateFolder(dirspec)242 return `mkdirSync operation succeeded. '${dirspec}'`243 }244 return `mkdirSync operation failed. '${dirspec}'`245}246247const mkdirsSync = function filesystem_mkdirsSync(spec) {248 // (spec: string): string249250 let dirs = split(absolute(spec))251 dirs.reduce((acc, curr) => {252 const specs = resolve(cwd, acc, curr)253 if (!existsdirSync(specs)) mkdirSync(specs)254 return specs255 }, NONE)256 return `mkdirsSync operation succeeded '${spec}'`257}258259const copydirSync = function filesystem_copydirSync(from, to) {260 // (from: string, to: string): string261262 FSO.CopyFolder(from, to)263 return `copydirSync operation succeeded '${dirspec}'`264}265266const download = function filesystem_download(url, saveFile) {267 // (url: string, saveFile?: string): Buffer268269 http.Open('GET', url, false)270 http.Send()271 if (http.status === 200) {272 if (saveFile != null) return writeFileSync(saveFile, http.responseBody)273 else return http.responseBody274 } else throw new Error(`filesystem_download Error status: ${http.status}`)275}276277const readdirsSync = function filesystem_readdirsSync(spec, callback) {278 // (spec: string, callback: function): any[]279280 let children = []281282 let files = new Enumerator(FSO.GetFolder(spec).Files)283 let dirs = new Enumerator(FSO.GetFolder(spec).SubFolders)284285 if (typeof callback === _FUNCTION) {286 files.forEach((node) => children.push(callback(node, null)))287 dirs.forEach((node) => children.push(callback(null, node)))288 return children289 } else {290 files.forEach((node) =>291 children.push({292 name: node.Name,293 path: absolute(node.Path),294 type: 'file'295 })296 )297 dirs.forEach((node) =>298 children.push({299 name: node.Name,300 path: absolute(node.path),301 type: 'directory',302 children: readdirsSync(absolute(node.path))303 })304 )305 return children.sort((a, b) => (a.name.toLowerCase() > b.name.toLowerCase() ? 1 : -1))306 }307}308309const readdirSync = function filesystem_readdirSync(spec) {310 // (spec: string): string[]311312 return readdirsSync(spec, (file, dir) => {313 if (file) return file.name314 else return dir.name315 })316}317318const deletedirSync = function filesystem_deletedirSync(dirspec) {319 // (dirspec: string): string320321 if (relative(cwd, dirspec).startsWith('..') && !allow(security.unsafe))322 throw new Error(323 '`--unsafe` or `--danger` command line arguments are required to delete outside the current directory'324 )325 try {326 FSO.DeleteFolder(dirspec)327 return `deletedirSync operation succeeded '${dirspec}'`328 } catch (err) {329 return `deletedirSync operation failed '${dirspec}'`330 }331}332333const encodeBuffer = function filesystem_encodeBuffer(buff, output_encode, input_encode) {334 // (buff: Buffer, output_encode: string, input_encode?: string): Buffer335336 const spec = resolve(process.cwd(), genGUID())337 try {338 writeFileSync(spec, buff)339 const text = readTextFileSync(spec, input_encode || null)340 writeTextFileSync(spec, text, output_encode)341 const res = readFileSync(spec)342 deleteFileSync(spec)343 return res344 } catch (err) {345 throw err346 } finally {347 if (existsFileSync(spec)) deleteFileSync(spec)348 }349}350351const statSync = function filesystem_statSync(spec) {352 // (spec: string): FileStat353354 const FSO = require('Scripting.FileSystemObject')355 const file = FSO.getFile(spec.split('/').join('\\'))356 return {357 atimeMs: new Date(file.DateLastAccessed).getTime(),358 mtimeMs: new Date(file.DateLastModified).getTime(),359 ctimeMs: new Date(file.DateCreated).getTime(),360 atime: new Date(file.DateLastAccessed),361 mtime: new Date(file.DateLastModified),362 ctime: new Date(file.DateCreated),363 size: file.Size364 }365}366367module.exports = {368 readFileSync,369 readTextFileSync,370 readByteFileSync,371 readdirsSync,372 readdirSync,373374 writeFileSync,375 writeTextFileSync,376377 exists,378 existsSync,379 existsFileSync,380 existsdirSync,381382 copyFileSync,383 copydirSync,384385 moveFileSync,386387 mergeFileSync,388389 deleteFileSync,390 deletedirSync,391392 mkdirSync,393 mkdirsSync,394395 download,396 BufferToText,397 ByteToText,398 encodeBuffer,399400 statSync
...
resolve.js
Source:resolve.js
1#!/usr/bin/env node2'use strict';3const fs = require('fs');4const http = require('http');5const https = require('https');6const yaml = require('yaml');7const fetch = require('node-fetch-h2');8const resolver = require('./index.js');9let argv = require('yargs')10 .string('output')11 .alias('o','output')12 .describe('output','file to output to')13 .default('output','resolved.yaml')14 .count('quiet')15 .alias('q','quiet')16 .describe('quiet','reduce verbosity')17 .count('verbose')18 .default('verbose',2)19 .alias('v','verbose')20 .describe('verbose','increase verbosity')21 .demand(1)22 .argv;23let filespec = argv._[0];24let options = {resolve: true};25options.verbose = argv.verbose;26if (argv.quiet) options.verbose = options.verbose - argv.quiet;27options.fatal = true;28if (filespec.startsWith('https')) options.agent = new https.Agent({ keepAlive: true })29else if (filespec.startsWith('http')) options.agent = new http.Agent({ keepAlive: true });30function main(str,source,options){31 let input = yaml.parse(str,{schema:'core'});32 resolver.resolve(input,source,options)33 .then(function(options){34 if (options.agent) {35 options.agent.destroy();36 }37 fs.writeFileSync(argv.output,yaml.stringify(options.openapi),'utf8');38 })39 .catch(function(err){40 console.warn(err);41 });42}43if (filespec && filespec.startsWith('http')) {44 console.warn('GET ' + filespec);45 fetch(filespec, {agent:options.agent}).then(function (res) {46 if (res.status !== 200) throw new Error(`Received status code ${res.status}`);47 return res.text();48 }).then(function (body) {49 main(body,filespec,options);50 }).catch(function (err) {51 console.warn(err);52 });53}54else {55 fs.readFile(filespec,'utf8',function(err,data){56 if (err) {57 console.warn(err);58 }59 else {60 main(data,filespec,options);61 }62 });...
Using AI Code Generation
1var wptools = require('wptools');2var fs = require('fs');3var options = {4};5var page = wptools.page('Albert Einstein', options);6page.get(function(err, info) {7 if (err) {8 console.log(err);9 } else {10 console.log(info.imageinfo);11 console.log(info.imageinfo[0].url);12 console.log(info.imageinfo[0].descriptionurl);13 console.log(info.imageinfo[0].descriptionshorturl);14 console.log(info.imageinfo[0].extmetadata.ImageDescription.value);15 console.log(info.imageinfo[0].extmetadata.Artist.value);16 console.log(info.imageinfo[0].extmetadata.DateTime.value);17 console.log(info.imageinfo[0].extmetadata.GPSLatitude.value);18 console.log(info.imageinfo[0].extmetadata.GPSLongitude.value);19 console.log(info.imageinfo[0].extmetadata.GPSAltitude.value);20 console.log(info.imageinfo[0].extmetadata.GPSDOP.value);21 console.log(info.imageinfo[0].extmetadata.GPSMapDatum.value);22 console.log(info.imageinfo[0].extmetadata.GPSDestBearing.value);23 console.log(info.imageinfo[0].extmetadata.GPSDestDistance.value);24 console.log(info.imageinfo[0].extmetadata.GPSProcessingMethod.value);25 console.log(info.imageinfo[0].extmetadata.GPSAreaInformation.value);26 console.log(info.imageinfo[0].extmetadata.GPSDateStamp.value);27 console.log(info.imageinfo[0].extmetadata.GPSDifferential.value);28 console.log(info.imageinfo[0].extmetadata.GPSHPositioningError.value);29 console.log(info.imageinfo[0].extmetadata.ImageUniqueID.value);30 console.log(info.imageinfo[0].extmetadata.Make.value);31 console.log(info.imageinfo[0].extmetadata.Model.value);32 console.log(info.imageinfo[0].extmetadata.Orientation.value);33 console.log(info.imageinfo[0].extmetadata.XResolution.value);34 console.log(info.imageinfo[0].extmetadata.YResolution.value);35 console.log(info.imageinfo[0].extmetadata.ResolutionUnit.value);36 console.log(info.imageinfo[0].extmetadata.Software.value);37 console.log(info.imageinfo[0].extmetadata.DateTimeOriginal
Using AI Code Generation
1var wptools = require('wptools');2var fs = require('fs');3var path = require('path');4var file = path.join(__dirname, 'test.jpg');5var options = {6};7wptools.page(options).get().then(function(result) {8 console.log(result);9});10var wptools = require('wptools');11var fs = require('fs');12var path = require('path');13var file = path.join(__dirname, 'test.jpg');14var options = {15};16wptools.page(options).get().then(function(result) {17 console.log(result);18});19var wptools = require('wptools');20var fs = require('fs');21var path = require('path');22var file = path.join(__dirname, 'test.jpg');23var options = {24};25wptools.page(options).get().then(function(result) {26 console.log(result);27});28var wptools = require('wptools');29var fs = require('fs');30var path = require('path');31var file = path.join(__dirname, 'test.jpg');32var options = {
Using AI Code Generation
1var wpt = require('webpagetest');2var fs = require('fs');3var wpt = new WebPageTest('www.webpagetest.org');4var fileSpec = fs.readFileSync('spec.json');5var spec = JSON.parse(fileSpec);6wpt.runTest(spec, function(err, data) {7 if (err) return console.error(err);8 console.log('Test submitted. Poll for results at %s/jsonResult.php?test=%s', wpt.server, data.data.testId);9});
Using AI Code Generation
1var wptools = require('wptools');2var fs = require('fs');3var path = require('path');4var file = path.resolve(__dirname, 'test.txt');5var fileSpec = new wptools.FileSpec(file);6fileSpec.on('error', function(err) {7 console.log('Error: ', err);8});9fileSpec.on('complete', function(data) {10 console.log('Complete: ', data);11});12fileSpec.on('progress', function(data) {13 console.log('Progress: ', data);14});15fileSpec.on('timeout', function(data) {16 console.log('Timeout: ', data);17});18fileSpec.on('missing', function(data) {19 console.log('Missing: ', data);20});21fileSpec.on('exists', function(data) {22 console.log('Exists: ', data);23});24fileSpec.on('new', function(data) {25 console.log('New: ', data);26});27fileSpec.on('duplicate', function(data) {28 console.log('Duplicate: ', data);29});30fileSpec.on('bad', function(data) {31 console.log('Bad: ', data);32});33fileSpec.on('skipped', function(data) {34 console.log('Skipped: ', data);35});36fileSpec.on('upload', function(data) {37 console.log('Upload: ', data);38});39fileSpec.on('uploaded', function(data) {40 console.log('Uploaded: ', data);41});42fileSpec.on('replaced', function(data) {43 console.log('Replaced: ', data);44});45fileSpec.on('deleted', function(data) {46 console.log('Deleted: ', data);47});48fileSpec.on('reverted', function(data) {49 console.log('Reverted: ', data);50});51fileSpec.on('unreverted', function(data) {52 console.log('Unreverted: ', data);53});54fileSpec.on('moved', function(data) {55 console.log('Moved: ', data);56});57fileSpec.on('renamed', function(data) {58 console.log('Renamed: ', data);59});60fileSpec.on('log', function(data) {61 console.log('Log: ', data);62});63fileSpec.on('info', function(data) {64 console.log('Info: ', data);65});66fileSpec.on('warning', function(data) {67 console.log('Warning: ', data);68});69fileSpec.on('
Using AI Code Generation
1var wptools = require('wptools');2var fs = require('fs');3var path = require('path');4var file = path.join(__dirname, 'file.txt');5var fileSpec = new wptools.FileSpec(file);6console.log(fileSpec.name);7console.log(fileSpec.type);8console.log(fileSpec.size);9console.log(fileSpec.modified);10console.log(fileSpec.path);
Using AI Code Generation
1var wptools = require('wptools');2var fs = require('fs');3var file = fs.readFileSync('test.txt').toString().split("\n");4var i;5for(i in file) {6 var page = wptools.page(file[i]);7 page.get(function(err, resp) {8 console.log(resp.data.image);9 });10}
Using AI Code Generation
1var wptools = require('../index.js');2var fs = require('fs');3var path = require('path');4var file = new wptools.FileSpec(path.join(__dirname, 'test.pdf'));5file.extractText(function(err, text) {6 if (err) {7 console.log(err);8 } else {9 console.log(text);10 }11});12This module is based on [wptools](
Using AI Code Generation
1var fs = require('fs');2var wpt = require('../index.js');3var config = JSON.parse(fs.readFileSync('./config.json', 'utf8'));4var options = {5};6wpt.runTest(options, function(err, data)
Using AI Code Generation
1var wptools = require('wptools');2var fs = require('fs');3var options = {4};5wptools.page(options).get(function(err, info) {6 if (err) {7 console.log(err);8 } else {9 console.log(info);10 }11});12var wptools = require('wptools');13var fs = require('fs');14var options = {15};16wptools.page(options).get(function(err, info) {17 if (err) {18 console.log(err);19 } else {20 console.log(info);21 }22});23var wptools = require('wptools');24var fs = require('fs');25var options = {26};27wptools.page(options).get(function(err, info) {28 if (err) {29 console.log(err);30 } else {31 console.log(info);32 }33});34var wptools = require('wptools');35var fs = require('fs');36var options = {37};38wptools.page(options).get(function(err, info
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!