How to use escapeString method in tracetest

Best JavaScript code snippet using tracetest

route_api.js

Source:route_api.js Github

copy

Full Screen

1const app = require('./app.js');2const router_module = require('./router_module.js');3const path = require('path');4const fs = require('fs');5const Jimp = require('jimp');6//======================================================== function Global 7const SaveSession = (req, sidaccount, semail, spassword) => {8 req.session.idaccount = sidaccount;9 req.session.email = semail;10 req.session.password = spassword;11 console.log('login session : ' + req.session.email);12}13//======================================================== 14exports.logout = (req, res) => {15 req.session.idaccount = null;16 req.session.email = null;17 req.session.password = null;18 res.send('true');19}20exports.login = (req, res) => {21 let email = router_module.EscapeString(req.body.email);22 let password = router_module.EscapeString(req.body.password);23 const CheckEmailandPassword = () => {24 new Promise((resolve) => { router_module.OpenQuery('SELECT ID FROM dbmaccount where email="' + email + '" and password="' + password + '";', resolve) })25 .then((result) => {26 if (result.dataset.length > 0) {27 SaveSession(req, result.dataset[0].ID, email, password)28 res.send('true')29 } else res.send("password not valid")30 }).catch((result) => { res.send(result.error) });31 }32 const CheckEmail = () => {33 new Promise((resolve) => { router_module.OpenQuery('SELECT ID FROM dbmaccount where email="' + email + '";', resolve) })34 .then((resultCheckEmail) => {35 if (resultCheckEmail.dataset.length > 0) CheckEmailandPassword()36 else res.send("email not rigistered")37 }).catch((result) => { res.send(result.error) });38 }39 CheckEmail()40}41exports.registeraccount = (req, res) => {42 let displayname = router_module.EscapeString(req.body.displayname);43 let email = router_module.EscapeString(req.body.email);44 let password = router_module.EscapeString(req.body.password);45 const SaveRegisterAccount = () => {46 new Promise((resolve) => { router_module.OpenQuery("INSERT INTO dbmaccount (displayname,email,password) VALUES ('" + displayname + "','" + email + "','" + password + "'); \n SELECT (LAST_INSERT_ID()) AS idaccount;", resolve) })47 .then((result) => {48 if (result.dataset.length > 0) {49 console.log('Register : ' + email)50 SaveSession(req, result.dataset[1][0].idaccount, email, password)51 res.send('true')52 } else res.send("Failed to register")53 }).catch((result) => { res.send(result.error) });54 }55 new Promise((resolve) => { router_module.OpenQuery('SELECT * FROM dbmaccount where email="' + email + '";', resolve) })56 .then((result) => {57 if (result.dataset.length > 0) res.send("email already exist ")58 else SaveRegisterAccount()59 }).catch((result) => { res.send(result.error) });60}61exports.adminlogin = (req, res) => {62 let susername = router_module.EscapeString(req.body.username);63 let spassword = router_module.EscapeString(req.body.password);64 new Promise((resolve) => { router_module.OpenQuery('SELECT * FROM dbmaccount where Email="' + susername + '" and Password="' + spassword + '"', resolve) })65 .then((result) => {66 if (result.dataset.length > 0) {67 req.session.idadmin = result.dataset[0].ID;68 req.session.usernameadmin = susername;69 req.session.passwordadmin = spassword;70 res.send('true');71 } else {72 req.session.usernameadmin = '';73 req.session.passwordadmin = '';74 res.send('Can\'t Login');75 }76 }).catch((result) => { res.send(result.error) })77}78exports.productadd = (req, res) => {79 let mode = router_module.EscapeString(req.query.mode)80 let iddata = router_module.EscapeString(req.query.iddata)81 let sku = router_module.EscapeString(req.query.sku)82 let nameproduct = router_module.EscapeString(req.query.nameproduct)83 let category = router_module.EscapeString(req.query.category)84 let urlimage = router_module.EscapeString(req.query.urlimage)85 let unit = router_module.EscapeString(req.query.unit)86 let price = router_module.EscapeString(req.query.price)87 let stock = router_module.EscapeString(req.query.stock)88 let description = router_module.EscapeString(req.query.description)89 let isShowQty = router_module.EscapeString(req.query.isShowQty)90 let isShow = router_module.EscapeString(req.query.isShow)91 let idcategory = null;92 const SaveData = () => {93 let ssqlSave = '';94 if (mode == 'edit') ssqlSave = "UPDATE dbmproduct SET SKU='" + sku + "', nameproduct='" + nameproduct + "', imageurl='" + urlimage + "', unit='" + unit + "', price='" + price + "', stock='" + stock + "', description='" + description + "', idcategory='" + idcategory + "', isShowStock='" + isShowQty + "', isShow='" + isShow + "' where ID='" + iddata + "'";95 else if (mode == 'add') ssqlSave = "INSERT INTO dbmproduct (SKU,nameproduct,imageurl,unit,price,stock,description,idcategory,isShowStock,isShow) VALUES ('" + sku + "','" + nameproduct + "','" + urlimage + "','" + unit + "','" + price + "','" + stock + "','" + description + "','" + idcategory + "','" + isShowQty + "','" + isShow + "')";96 new Promise((resolve) => { router_module.ExecQuery(ssqlSave, resolve) })97 .then((result) => {98 if (result.err) res.send("false")99 else res.send('true')100 }).catch((result) => { res.send(result.error) });101 }102 const CheckCateogry = () => {103 new Promise((resolve) => { router_module.OpenQuery('SELECT ID FROM dbmcategory WHERE NameCategory="' + category + '";', resolve) })104 .then((result) => {105 if (result.dataset.length > 0) {106 idcategory = result.dataset[0].ID107 SaveData()108 } else res.send("tipe category tidak valid")109 }).catch((result) => { res.send(result.error) });110 }111 let ssql = '';112 if (mode == 'add') ssql = 'SELECT * FROM dbmproduct where isDelete=0 and nameproduct="' + nameproduct + '";'113 else ssql = 'SELECT * FROM dbmproduct where isDelete=0 and ID="' + iddata + '";'114 new Promise((resolve) => { router_module.OpenQuery(ssql, resolve) })115 .then((result) => {116 if (mode == 'add') {117 if (result.dataset.length > 0) res.send("product name already exist ")118 else CheckCateogry();119 } else if (mode == 'edit') {120 if (result.dataset.length = 0) res.send("data product not found ")121 else CheckCateogry()122 }123 })124 .catch((result) => {125 res.send(result.error)126 });127}128exports.productdelete = (req, res) => {129 let iddata = router_module.EscapeString(req.params.iddata)130 new Promise((resolve) => { router_module.ExecQuery("UPDATE `dbmproduct` SET IsDelete=1 WHERE ID='" + iddata + "';", resolve) })131 .then((result) => {132 if (result.err) res.send("false")133 else res.send('true')134 }).catch((result) => { res.send(result.error) });135}136exports.cartadd = (req, res) => {137 let idproduct = router_module.EscapeString(req.params.itemid)138 let qty = router_module.EscapeString(req.params.qty)139 const AddToCart = () => {140 let itemcart = []141 if (req.session.itemcart != undefined) itemcart = req.session.itemcart142 let podcart = new router_module.Cartdataobject143 let flag = podcart.add(itemcart, idproduct, qty)144 if (flag == false) podcart.edit(itemcart, idproduct, qty)145 req.session.itemcart = itemcart146 res.send('true')147 }148 const CheckProductAvailable = () => {149 new Promise((resolve) => { router_module.OpenQuery('SELECT * FROM dbmproduct where id="' + idproduct + '";', resolve) })150 .then((result) => {151 if (result.dataset.length > 0) AddToCart()152 else res.send("product tidak di temukan ")153 }).catch((result) => { res.send(result.error) });154 }155 CheckProductAvailable()156}157exports.carteditqty = (req, res) => {158 let itemid = router_module.EscapeString(req.params.itemid)159 let qty = router_module.EscapeString(req.params.qty)160 const UpdateProduct = () => {161 let itemcart = []162 if (req.session.itemcart != undefined) itemcart = req.session.itemcart163 var podcart = new router_module.Cartdataobject164 podcart.edit(itemcart, itemid, qty)165 res.send('true')166 }167 UpdateProduct()168}169exports.cartdelete = (req, res) => {170 let itemid = router_module.EscapeString(req.params.itemid)171 let itemcart = []172 if (req.session.itemcart != undefined) itemcart = req.session.itemcart173 var podcart = new router_module.Cartdataobject174 podcart.delete(itemcart, req.params.itemid) + ' delete item :' + itemid175 req.session.itemcart = itemcart176 res.send('true')177}178exports.adminchangedataorder = (req, res) => {179 let transid = router_module.EscapeString(req.body.transid)180 let docnumber = router_module.EscapeString(req.body.docnumber)181 let statuspayment = router_module.EscapeString(req.body.statuspayment)182 let statustrans = router_module.EscapeString(req.body.statustrans)183 let dataDocument = []184 const UpdateHistory = () => {185 let ssql = ''186 let memoStatusTrans = ''187 let memoStatusPayment = ''188 let flag = false189 if (dataDocument.StatusPayment != statuspayment) {190 //notyet,waiting,success,reject191 switch (statuspayment) {192 case 'notyet':193 memoStatusPayment = "Belum melakukan pembayaran";194 break;195 case 'waiting':196 memoStatusPayment = "Pembayaran sedang diproses";197 break;198 case 'success':199 memoStatusPayment = "Pembarayan telah dikonfirmasi";200 break;201 case 'reject':202 memoStatusPayment = "Pembarayan ditolak";203 break;204 default:205 memoStatusPayment = "-";206 }207 ssql = `INSERT INTO dbttranshistory (TransID,DocNumber,Status,Notes,TimeCreated) values ("` + dataDocument.ID + `","` + dataDocument.DocNumber + `","new","` + memoStatusPayment + `",now());`208 flag = true209 }210 if (dataDocument.Status != statustrans) {211 // open,processed,awaiting,complete,canceled212 switch (statustrans) {213 case 'open':214 memoStatusTrans = "Transaksi diperbarui";215 break;216 case 'processed':217 memoStatusTrans = "Transaksi diproses";218 break;219 case 'awaiting':220 memoStatusTrans = "Transaksi sedang diproses";221 break;222 case 'complete':223 memoStatusTrans = "Transaksi berhasil";224 break;225 case 'canceled':226 memoStatusTrans = "Transaksi dibatalkan";227 break;228 default:229 memoStatusTrans = "-";230 }231 ssql = ssql + `\n INSERT INTO dbttranshistory (TransID,DocNumber,Status,Notes,TimeCreated) values ("` + dataDocument.ID + `","` + dataDocument.DocNumber + `","new","` + memoStatusTrans + `",now());`232 flag = true233 }234 if (flag) {235 new Promise((resolve) => { router_module.ExecQuery(ssql, resolve) })236 .then((result) => {237 if (result.err) res.send("Gagal menyimpan")238 else res.send('true')239 }).catch((result) => { res.send(result.error) });240 } else {241 res.send('true')242 }243 }244 const UpdateData = () => {245 let ssql = 'UPDATE `dbttransdoc` SET `Status`="' + statustrans + '", `StatusPayment`="' + statuspayment + '" WHERE `ID`="' + transid + '"'246 new Promise((resolve) => { router_module.ExecQuery(ssql, resolve) })247 .then((result) => {248 if (result.err) res.send("Gagal menyimpan")249 else UpdateHistory()250 }).catch((result) => { res.send(result.error) });251 }252 const CheckData = () => {253 new Promise((resolve) => { router_module.OpenQuery('SELECT ID,DocNumber,Status,StatusPayment FROM dbttransdoc where Docnumber="' + docnumber + '";', resolve) })254 .then((result) => {255 if (result.dataset.length > 0) {256 dataDocument = result.dataset[0]257 UpdateData()258 } else res.send("Data invalid")259 }).catch((result) => { res.send(result.error) });260 }261 CheckData()262}263exports.profilesave = (req, res) => {264 let idaccount = req.session.idaccount265 let displayname = router_module.EscapeString(req.body.displayname)266 let telp = router_module.EscapeString(req.body.telp)267 let city = router_module.EscapeString(req.body.city)268 let address = router_module.EscapeString(req.body.address)269 let codepos = router_module.EscapeString(req.body.codepos)270 const UpdateData = () => {271 let ssql = 'UPDATE dbmaccount SET DisplayName="' + displayname + '", Phone="' + telp + '", Address="' + address + '", City="' + city + '", CodePos="' + codepos +272 '" where ID="' + idaccount + '";';273 let pool = app.module_app();274 pool.getConnection(function (err, connection) {275 if (err) throw err;276 connection.query(ssql, function (err, result) {277 connection.release();278 if (err) {279 console.log(err)280 res.send('false')281 } else res.send('true')282 });283 });284 }285 new Promise((resolve) => { router_module.OpenQuery('SELECT ID FROM dbmaccount where id="' + idaccount + '";', resolve) })286 .then((result) => {287 if (result.dataset.length > 0) UpdateData()288 else res.send("/relogin")289 }).catch((result) => { res.send(result.error) });290}291exports.transactionsender = (req, res) => {292 let idaccount = req.session.idaccount293 let namereceipt = router_module.EscapeString(req.query.namereceipt)294 let emailreceipt = router_module.EscapeString(req.query.emailreceipt)295 let numberreceipt = router_module.EscapeString(req.query.numberreceipt)296 let city = router_module.EscapeString(req.query.city)297 let address = router_module.EscapeString(req.query.address)298 let codePos = router_module.EscapeString(req.query.codePos)299 let notes = router_module.EscapeString(req.query.notes)300 if ((idaccount == 'undefined') || (idaccount == '') || (idaccount == null)) idaccount = 0301 const SaveTransaction = () => {302 let itemcart = []303 if (req.session.itemcart != undefined) itemcart = req.session.itemcart304 let ssqldata = '';305 for (let i = 0; i < itemcart.length; i++) ssqldata = ssqldata + `\n (@TransID,@DocNumber,"` + itemcart[i].itemid + `","` + itemcart[i].qty + `","0"),`306 ssqldata = ssqldata.replace(/.$/, ";") // replace last character307 let ssqlInsertTransaction = `INSERT INTO dbttransdoc (IDAccount,TimeCreated,TimeUpdated,STATUS,ShippingRecipient,ShippingEmail,ShippingPhone,ShippingAddress,ShippingCity,ShippingCodePos,PaymentProof,ShippingPaymentPerson,ShippingPaymentNumber,ShippingPaymentBank,StatusPayment,Notes)`308 + `SELECT "` + idaccount + `",NOW(),NOW(),"open","` + namereceipt + `","` + emailreceipt + `","` + numberreceipt + `","` + address + `","` + city + `","` + codePos + `","","","","","notyet","` + notes + `";` + // data account309 `SELECT LAST_INSERT_ID() INTO @TransID;310 SET @DocNumber=(SELECT CONCAT(DATE_FORMAT(NOW(),"%d%m%y"),@TransID));311 UPDATE dbttransdoc SET DocNumber=@DocNumber WHERE ID=@TransID;312 INSERT INTO dbttransdetail (TransID, DocNumber,IDProduct,Qty,Price) VALUES `+ ssqldata + `313 UPDATE dbttransdetail a LEFT JOIN dbmproduct b ON a.IDProduct=b.ID SET a.Price=b.Price, a.Total=(b.Price*a.QTy) WHERE TransID=@TransID ;314 UPDATE dbttransdoc SET GrandTotal=(SELECT COALESCE(SUM(Price*Qty),0) FROM dbttransdetail WHERE DocNumber=@DocNumber) WHERE DocNumber=@DocNumber;315 INSERT INTO dbttranshistory (TransID,DocNumber,Status,Notes,TimeCreated) values (@TransID,@DocNumber,"new","Transaksi dibuat",now());316 SELECT DocNumber,DATE_FORMAT(TimeCreated,"%d %b %Y") as Tanggal FROM dbttransdoc where ID=@TransID;317 `318 new Promise((resolve) => { router_module.OpenQuery(ssqlInsertTransaction, resolve) })319 .then((result) => {320 if (result.dataset[8].length > 0) {321 console.log('customer order')322 req.session.itemcart = []323 res.json({ status: true, invoice: result.dataset[8][0].DocNumber, tanggal: result.dataset[8][0].Tanggal })324 } else res.json({ status: false, message: 'Gagal melakukan pemesanan' })325 }).catch((result) => { res.send(result.error) });326 }327 const CheckifCartNull = () => {328 let itemcart = []329 if (req.session.itemcart != undefined) itemcart = req.session.itemcart330 if (itemcart.length != 0) SaveTransaction()331 else res.json({ status: false, message: 'Tidak bisa melanjutkan karena pemesanan daftar barang kosong' })332 }333 const CheckData = () => {334 if ((namereceipt == '') || (numberreceipt == '') ||335 (address == '') || (city == '') || (codePos == '')) {336 res.json({ status: false, message: 'Mohon lengkapi data pengiriman' })337 } else CheckifCartNull()338 }339 CheckData()340}341exports.filemanagersave = (req, res) => {342 let datafile = req.files.datafile343 let namefile = router_module.EscapeString(req.body.namefile)344 let namefiledata = null345 let iddata = null346 let spath = ''347 const ConvertThumbnail = () => {348 Jimp.read(uploadPath)349 .then(lenna => {350 return lenna351 .quality(60) // set JPEG quality352 .write(__dirname + '/temp/filesmanager/tmp_' + spath); // save353 })354 .catch(err => {355 console.error(err);356 });357 }358 const UpdateData = () => {359 let ssql = `Update dbmfilesmanager set NameFile="` + namefile + `", Path="` + spath + `" where ID="` + iddata + `"`360 new Promise((resolve) => { router_module.ExecQuery(ssql, resolve) })361 .then((result) => {362 if (result.err) res.send("false")363 else res.send('true')364 }).catch((result) => { res.send(result.error) });365 }366 function SaveFile() {367 spath = namefiledata + datafile.name368 uploadPath = __dirname + '/temp/filesmanager/' + spath;369 datafile.mv(uploadPath, function (err) {370 if (err) res.send('Gagal mengupload file')371 else{372 ConvertThumbnail()373 UpdateData()374 } 375 });376 }377 function SaveData() {378 // let ssql = `INSERT INTO dbmfilesmanager (NameFile,Path,TimeCreated) values ("`+namefile+`","`+spathFile+`",now());`379 let ssql = ` INSERT INTO dbmfilesmanager (TimeCreated)VALUES(NOW());380 SELECT CONCAT(DATE_FORMAT(NOW(),'%y%m%d'),LAST_INSERT_ID(),"-`+ namefile + `") AS namedata, LAST_INSERT_ID() as IDData;`381 new Promise((resolve) => { router_module.OpenQuery(ssql, resolve) })382 .then((result) => {383 if (result.dataset.length > 0) {384 namefiledata = result.dataset[1][0].namedata385 iddata = result.dataset[1][0].IDData386 SaveFile()387 } else res.send('false');388 }).catch((result) => { res.send(result.error) })389 }390 if (Object.keys(req.files).length == 0) res.send('No files were uploaded.')391 else SaveData()392}393exports.filemanagerdelete = (req, res) => {394 let iddata = router_module.EscapeString(req.params.iddata)395 let pathData = ''396 const DeleteFile = () => {397 fileData = __dirname + '/temp/filesmanager/' + pathData;398 fs.unlink(fileData, function (err) {399 if (err) throw err;400 res.send('true')401 });402 }403 const DeleteData = () => {404 new Promise((resolve) => { router_module.ExecQuery("Delete from `dbmfilesmanager` WHERE ID='" + iddata + "';", resolve) })405 .then((result) => {406 if (result.err) res.send("false")407 else DeleteFile()408 }).catch((result) => { res.send(result.error) });409 }410 const ChooseData = () => {411 let ssql = `SELECT * FROM dbmfilesmanager where ID="` + iddata + `"`412 new Promise((resolve) => { router_module.OpenQuery(ssql, resolve) })413 .then((result) => {414 if (result.dataset.length > 0) {415 pathData = result.dataset[0].Path416 DeleteData()417 } else res.send('false');418 }).catch((result) => { res.send(result.error) })419 }420 ChooseData()421}422exports.clientpaymentupload = (req, res) => {423 let proof = req.files.proof424 let docnumber = router_module.EscapeString(req.body.docnumber)425 let bank = router_module.EscapeString(req.body.bank)426 let namebank = router_module.EscapeString(req.body.namebank)427 let numberbank = router_module.EscapeString(req.body.numberbank)428 let amount = router_module.EscapeString(req.body.amount)429 const ConvertThumbnail = () => {430 Jimp.read(uploadPath)431 .then(lenna => {432 return lenna433 .quality(60) // set JPEG quality434 .write( __dirname + '/temp/paymentproof/tmp_' + proof.name); // save435 })436 .catch(err => {437 console.error(err);438 });439 }440 function SaveFile() {441 if (Object.keys(req.files).length == 0) res.send('No files were uploaded.')442 else {443 uploadPath = __dirname + '/temp/paymentproof/' + proof.name;444 proof.mv(uploadPath, function (err) {445 if (err) res.send('Gagal mengupload file')446 else{447 ConvertThumbnail()448 SaveDataPayment(proof.name)449 } 450 });451 }452 }453 function SaveDataPayment(spathFile) {454 let ssql = `UPDATE dbttransdoc SET StatusPayment="waiting", PaymentProof='` + spathFile + `',ShippingPaymentPerson='` + namebank + `',ShippingPaymentNumber='` + numberbank + `',455 ShippingPaymentBank='` + bank + `',ShippingAmount='` + amount + `' WHERE DocNumber='` + docnumber + `';456 INSERT INTO dbttranshistory (TransID,DocNumber,Status,Notes,TimeCreated) values (0,"`+ docnumber + `","new","Upload pembayaran",now());`457 new Promise((resolve) => { router_module.ExecQuery(ssql, resolve) })458 .then((result) => {459 if (result.err) res.send("false")460 else res.send('true')461 }).catch((result) => { res.send(result.error) });462 }463 // Main464 new Promise((resolve) => { router_module.OpenQuery('SELECT * FROM dbttransdoc where DocNumber="' + docnumber + '";', resolve) })465 .then((result) => {466 if (result.dataset.length > 0) SaveFile()467 else res.send("Pembayaran invalid, Data invoice tidak di temukan !")468 }).catch((result) => { res.send(result.error) });469}470exports.bannersave = (req, res) => {471 let mode = req.query.mode472 let iddata = router_module.EscapeString(req.query.iddata)473 let judul = router_module.EscapeString(req.query.judul)474 let content = router_module.EscapeString(req.query.content)475 let urlimage = router_module.EscapeString(req.query.urlimage)476 let isshow = router_module.EscapeString(req.query.isshow)477 function SaveData() {478 let ssqlSave = '';479 if (mode == 'edit') ssqlSave = "UPDATE dbtbanner SET Caption='" + judul + "', Content='" + content + "', ImageUrl='" + urlimage + "', isShow='" + isshow + "' where ID='" + iddata + "'";480 else if (mode == 'add') ssqlSave = "INSERT INTO dbtbanner (Caption,Content,ImageUrl,isShow) VALUES ('" + judul + "','" + content + "','" + urlimage + "','" + isshow + "')";481 new Promise((resolve) => { router_module.ExecQuery(ssqlSave, resolve) })482 .then((result) => {483 if (result.err) res.send("false")484 else res.send('true')485 }).catch((result) => { res.send(result.error) });486 }487 if (mode == 'add') SaveData()488 else {489 let ssql = '';490 ssql = 'SELECT * FROM dbtbanner where ID="' + iddata + '";'491 new Promise((resolve) => { router_module.OpenQuery(ssql, resolve) })492 .then((result) => {493 if (result.dataset.length = 0) res.send("Data banner tidak ditemukan")494 else SaveData()495 })496 .catch((result) => {497 res.send(result.error)498 });499 }500}501exports.bannerdelete = (req, res) => {502 let iddata = router_module.EscapeString(req.params.iddata);503 new Promise((resolve) => { router_module.ExecQuery("Delete from `dbtbanner` WHERE ID='" + iddata + "';", resolve) })504 .then((result) => {505 if (result.err) res.send("false")506 else res.send('true')507 }).catch((result) => { res.send(result.error) });508}509exports.categorysave = (req, res) => {510 let mode = req.query.mode;511 let iddata = router_module.EscapeString(req.query.iddata);512 let nameCategory = router_module.EscapeString(req.query.namecategory);513 let urlimage = router_module.EscapeString(req.query.urlimage);514 function SaveData() {515 let ssqlSave = '';516 if (mode == 'edit') ssqlSave = "UPDATE dbmcategory SET NameCategory='" + nameCategory + "', ImageUrl='" + urlimage + "' where ID='" + iddata + "'";517 else if (mode == 'add') ssqlSave = "INSERT INTO dbmcategory (NameCategory, ImageUrl) VALUES ('" + nameCategory + "', '" + urlimage + "')";518 new Promise((resolve) => { router_module.ExecQuery(ssqlSave, resolve) })519 .then((result) => {520 if (result.err) res.send("false")521 else res.send('true')522 }).catch((result) => { res.send(result.error) });523 }524 if (mode == 'add') SaveData()525 else {526 let ssql = '';527 ssql = 'SELECT * FROM dbmcategory where ID="' + iddata + '";'528 new Promise((resolve) => { router_module.OpenQuery(ssql, resolve) })529 .then((result) => {530 if (result.dataset.length = 0) res.send("Data kategori tidak ditemukan")531 else SaveData()532 })533 .catch((result) => {534 res.send(result.error)535 });536 }537}538exports.categorydelete = (req, res) => {539 let iddata = router_module.EscapeString(req.params.iddata);540 // new Promise((resolve) => { router_module.ExecQuery("Delete from `dbmcategory` WHERE ID='" + iddata + "';", resolve) })541 new Promise((resolve) => { router_module.ExecQuery("Update `dbmcategory` Set isDelete=1 WHERE ID='" + iddata + "';", resolve) })542 .then((result) => {543 if (result.err) res.send("false")544 else res.send('true')545 }).catch((result) => { res.send(result.error) });546}547exports.folderfilemanager = (req, res) => {548 let idfile = req.params.idfile549 let spath = path.join(__dirname + '/temp/filesmanager') + '/' + idfile550 fs.access(spath, fs.F_OK, (err) => {551 if (err) {552 console.error(err)553 res.send('Data not found')554 return555 }556 res.sendfile(spath)557 })...

Full Screen

Full Screen

factory.js

Source:factory.js Github

copy

Full Screen

...81 var fields = getFields(contentsBlock.getInputTargetBlock('FIELDS'));82 var name = '';83 // Dummy inputs don't have names. Other inputs do.84 if (contentsBlock.type != 'input_dummy') {85 name = escapeString(contentsBlock.getFieldValue('INPUTNAME'));86 }87 var check = getOptTypesFrom(contentsBlock, 'TYPE');88 code.push(' this.' + TYPES[contentsBlock.type] +89 '(' + name + ')');90 if (check && check != 'null') {91 code.push(' .setCheck(' + check + ')');92 }93 if (align != 'LEFT') {94 code.push(' .setAlign(Blockly.ALIGN_' + align + ')');95 }96 for (var x = 0; x < fields.length; x++) {97 code.push(' .appendField(' + fields[x] + ')');98 }99 // Add semicolon to last line to finish the statement.100 code[code.length - 1] += ';';101 }102 contentsBlock = contentsBlock.nextConnection &&103 contentsBlock.nextConnection.targetBlock();104 }105 // Generate inline/external switch.106 if (rootBlock.getFieldValue('INLINE') == 'INT') {107 code.push(' this.setInputsInline(true);');108 }109 // Generate output, or next/previous connections.110 switch (rootBlock.getFieldValue('CONNECTIONS')) {111 case 'LEFT':112 code.push(connectionLine_('setOutput', 'OUTPUTTYPE'));113 break;114 case 'BOTH':115 code.push(connectionLine_('setPreviousStatement', 'TOPTYPE'));116 code.push(connectionLine_('setNextStatement', 'BOTTOMTYPE'));117 break;118 case 'TOP':119 code.push(connectionLine_('setPreviousStatement', 'TOPTYPE'));120 break;121 case 'BOTTOM':122 code.push(connectionLine_('setNextStatement', 'BOTTOMTYPE'));123 break;124 }125 code.push(" this.setTooltip('');");126 code.push(" }");127 }128 code.push("};");129 injectCode(code, 'languagePre');130}131/**132 * Create JS code required to create a top, bottom, or value connection.133 * @param {string} functionName JavaScript function name.134 * @param {string} typeName Name of type input.135 * @return {string} Line of JavaScript code to create connection.136 * @private137 */138function connectionLine_(functionName, typeName) {139 var type = getOptTypesFrom(getRootBlock(), typeName);140 if (type) {141 type = ', ' + type;142 }143 return ' this.' + functionName + '(true' + type + ');';144}145/**146 * Returns a field string and any config.147 * @param {!Blockly.Block} block Field block.148 * @return {string} Field string.149 */150function getFields(block) {151 var fields = [];152 while (block) {153 if (!block.disabled && !block.getInheritedDisabled()) {154 switch (block.type) {155 case 'field_static':156 // Result: 'hello'157 fields.push(escapeString(block.getFieldValue('TEXT')));158 break;159 case 'field_input':160 // Result: new Blockly.FieldTextInput('Hello'), 'GREET'161 fields.push('new Blockly.FieldTextInput(' +162 escapeString(block.getFieldValue('TEXT')) + '), ' +163 escapeString(block.getFieldValue('FIELDNAME')));164 break;165 case 'field_angle':166 // Result: new Blockly.FieldAngle(90), 'ANGLE'167 fields.push('new Blockly.FieldAngle(' +168 escapeString(block.getFieldValue('ANGLE')) + '), ' +169 escapeString(block.getFieldValue('FIELDNAME')));170 break;171 case 'field_checkbox':172 // Result: new Blockly.FieldCheckbox('TRUE'), 'CHECK'173 fields.push('new Blockly.FieldCheckbox(' +174 escapeString(block.getFieldValue('CHECKED')) + '), ' +175 escapeString(block.getFieldValue('FIELDNAME')));176 break;177 case 'field_colour':178 // Result: new Blockly.FieldColour('#ff0000'), 'COLOUR'179 fields.push('new Blockly.FieldColour(' +180 escapeString(block.getFieldValue('COLOUR')) + '), ' +181 escapeString(block.getFieldValue('FIELDNAME')));182 break;183 case 'field_variable':184 // Result:185 // new Blockly.FieldVariable('item'), 'VAR'186 var varname = block.getFieldValue('TEXT');187 varname = varname ? escapeString(varname) : 'null';188 fields.push('new Blockly.FieldVariable(' + varname + '), ' +189 escapeString(block.getFieldValue('FIELDNAME')));190 break;191 case 'field_variable_pointer':192 // Result:193 // new Blockly.FieldVariablePointer('item'), 'VAR'194 var varname = block.getFieldValue('TEXT');195 varname = varname ? escapeString(varname) : 'null';196 fields.push('new Blockly.FieldVariablePointer(' + varname + '), ' +197 escapeString(block.getFieldValue('FIELDNAME')));198 break;199 case 'field_variable_array':200 // Result:201 // new Blockly.FieldVariableArray('item'), 'VAR'202 var varname = block.getFieldValue('TEXT');203 varname = varname ? escapeString(varname) : 'null';204 fields.push('new Blockly.FieldVariableArray(' + varname + '), ' +205 escapeString(block.getFieldValue('FIELDNAME')));206 break;207 case 'field_variable_define':208 // Result:209 // new Blockly.FieldVariableArray('item'), 'VAR'210 var varname = block.getFieldValue('TEXT');211 varname = varname ? escapeString(varname) : 'null';212 fields.push('new Blockly.FieldVariableDefine(' + varname + '), ' +213 escapeString(block.getFieldValue('FIELDNAME')));214 break;215 case 'field_structure':216 // Result:217 // new Blockly.FieldVariableArray('item'), 'VAR'218 var varname = block.getFieldValue('TEXT');219 varname = varname ? escapeString(varname) : 'null';220 fields.push('new Blockly.FieldStructure(' + varname + '), ' +221 escapeString(block.getFieldValue('FIELDNAME')));222 break;223 case 'field_dropdown':224 // Result:225 // new Blockly.FieldDropdown([['yes', '1'], ['no', '0']]), 'TOGGLE'226 var options = [];227 for (var x = 0; x < block.optionCount_; x++) {228 options[x] = '[' + escapeString(block.getFieldValue('USER' + x)) +229 ', ' + escapeString(block.getFieldValue('CPU' + x)) + ']';230 }231 if (options.length) {232 fields.push('new Blockly.FieldDropdown([' +233 options.join(', ') + ']), ' +234 escapeString(block.getFieldValue('FIELDNAME')));235 }236 break;237 case 'field_image':238 // Result: new Blockly.FieldImage('http://...', 80, 60)239 var src = escapeString(block.getFieldValue('SRC'));240 var width = Number(block.getFieldValue('WIDTH'));241 var height = Number(block.getFieldValue('HEIGHT'));242 var alt = escapeString(block.getFieldValue('ALT'));243 fields.push('new Blockly.FieldImage(' +244 src + ', ' + width + ', ' + height + ', ' + alt + ')');245 break;246 }247 }248 block = block.nextConnection && block.nextConnection.targetBlock();249 }250 return fields;251}252/**253 * Escape a string.254 * @param {string} string String to escape.255 * @return {string} Escaped string surrouned by quotes.256 */257function escapeString(string) {258 if (JSON && JSON.stringify) {259 return JSON.stringify(string);260 }261 // Hello MSIE 8.262 return '"' + string.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"';263}264/**265 * Fetch the type(s) defined in the given input.266 * Format as a string for appending to the generated code.267 * @param {!Blockly.Block} block Block with input.268 * @param {string} name Name of the input.269 * @return {string} String defining the types.270 */271function getOptTypesFrom(block, name) {272 var types = getTypesFrom_(block, name);273 if (types.length == 0) {274 return '';275 } else if (types.length == 1) {276 return types[0];277 } else if (types.indexOf('null') != -1) {278 return 'null';279 } else {280 return '[' + types.join(', ') + ']';281 }282}283/**284 * Fetch the type(s) defined in the given input.285 * @param {!Blockly.Block} block Block with input.286 * @param {string} name Name of the input.287 * @return {!Array.<string>} List of types.288 * @private289 */290function getTypesFrom_(block, name) {291 var typeBlock = block.getInputTargetBlock(name);292 var types;293 if (!typeBlock || typeBlock.disabled) {294 types = [];295 } else if (typeBlock.type == 'type_other') {296 types = [escapeString(typeBlock.getFieldValue('TYPE'))];297 } else if (typeBlock.type == 'type_group') {298 types = [];299 for (var n = 0; n < typeBlock.typeCount_; n++) {300 types = types.concat(getTypesFrom_(typeBlock, 'TYPE' + n));301 }302 // Remove duplicates.303 var hash = Object.create(null);304 for (var n = types.length - 1; n >= 0; n--) {305 if (hash[types[n]]) {306 types.splice(n, 1);307 }308 hash[types[n]] = true;309 }310 } else {311 types = [escapeString(typeBlock.valueType)];312 }313 return types;314}315/**316 * Update the generator code.317 */318function updateGenerator() {319 function makeVar(root, name) {320 name = name.toLowerCase().replace(/\W/g, '_');321 return ' var ' + root + '_' + name;322 }323 var language = document.getElementById('language').value;324 var code = [];325 code.push("Blockly." + language + "['" + blockType +...

Full Screen

Full Screen

_TextReader.js

Source:_TextReader.js Github

copy

Full Screen

1'use strict'2import {UnescapeSJIS, UnescapeEUCJP, UnescapeJIS7, UnescapeJIS8, 3 UnescapeUnicode, UnescapeUTF7, UnescapeUTF8, UnescapeUTF16LE} from '../third_party/ecl'4/*global Buffer*/5const _integerPattern = new RegExp(/^(-|\+)?\d+;?/)6const _floatPattern = new RegExp(/^(-|\+)?(\d)*\.(\d)*;?/)7const _wordPattern = new RegExp(/^\w+/)8const _linePattern = new RegExp(/^.*\n/)9/**10 * TextReader class11 * @access public12 */13export default class TextReader {14 /**15 * constructor16 * @access public17 * @constructor18 * @param {Buffer|ArrayBuffer} data -19 * @param {string} encoding -20 */21 constructor(data, encoding = 'utf-8') {22 /**23 * @access private24 * @type {number}25 */26 this._pos = 027 this._partialText = ''28 this._partialOffset = 029 this._partialStep = 20030 this._partialMinLength = 10031 /**32 * @access private33 * @type {boolean}34 */35 this._eof = true36 /**37 *38 * @access public39 * @type {Buffer}40 */41 this.buffer = null42 if(data instanceof Buffer){43 this.buffer = data44 }else{45 this.buffer = Buffer.from(data)46 }47 /**48 *49 * @access public50 * @type {boolean}51 */52 //this.bigEndian = bigEndian53 /**54 *55 * @access public56 * @type {string}57 */58 this.encoding = encoding59 // prepare buffered text60 this._addPartialText()61 }62 /**63 * @access public64 * @param {number} length - length of data to skip65 * @param {boolean} noAssert -66 * @returns {void}67 */68 skip(length, noAssert = false) {69 this._moveIndex(length)70 if(!noAssert){71 this._check()72 }73 }74 /**75 *76 * @access public77 * @param {number} length - length of data to read78 * @param {?string} [encoding = null] -79 * @returns {string} -80 */81 readString(length, encoding = null) {82 const str = this._partialText.substring(0, length)83 this._moveIndex(str.length)84 }85 /**86 *87 * @access public88 * @param {number} length - 89 * @param {boolean} signed -90 * @returns {number} -91 */92 readInteger(length, signed) {93 const str = this._getString(_integerPattern)94 const val = parseInt(str[0], 10)95 return val96 }97 /**98 *99 * @access public100 * @returns {number} -101 */102 readUnsignedByte() {103 return this.readInteger(1, false)104 }105 /**106 *107 * @access public108 * @returns {number} -109 */110 readUnsignedShort() {111 return this.readInteger(2, false)112 }113 /**114 *115 * @access public116 * @returns {number} -117 */118 readUnsignedInt() {119 return this.readInteger(4, false)120 }121 /**122 *123 * @access public124 * @returns {number} -125 */126 readInt() {127 return this.readInteger(4, true)128 }129 /**130 *131 * @access public132 * @returns {number} -133 */134 readFloat() {135 const str = this._getString(_floatPattern)136 const val = parseFloat(str[0])137 return val138 }139 /**140 *141 * @access public142 * @returns {number} -143 */144 readDouble() {145 return this.readFloat()146 }147 /**148 *149 * @access public150 * @param {number} length -151 * @returns {Buffer} -152 */153 readData(length) {154 const start = this._pos155 this._pos += length156 return this.buffer.slice(start, this._pos)157 }158 readWord() {159 const str = this._getString(_wordPattern)160 return (str !== null ? str[0] : null)161 }162 readLine() {163 const str = this._getString(_linePattern)164 return (str !== null ? str[0] : null)165 }166 readPattern(pattern) {167 return this._getString(pattern)168 }169 /**170 *171 * @access private172 * @returns {void}173 */174 _check() {175 }176 /**177 * 178 * @access private179 * @param {number[]} data - data to escape180 * @param {?string} [encoding = null] -181 * @returns {string} - escaped string182 */183 _escapeLE(data, encoding) {184 const length = data.length185 let escapeString = ''186 for(let i=0; i<length; i++){187 const charCode = data.charCodeAt(i)188 if(charCode === 0){189 break190 }191 else if(charCode < 16){192 escapeString += '%0' + charCode.toString(16)193 }else{194 escapeString += '%' + charCode.toString(16)195 }196 }197 return escapeString198 }199 /**200 * 201 * @access private202 * @param {number[]} data - data to escape203 * @param {?string} [encoding = null] -204 * @returns {string} - escaped string205 */206 _escapeBE(data, encoding) {207 const length = data.length208 let escapeString = ''209 for(let i=0; i<length; i++){210 const charCode1 = data.charCodeAt(i)211 if(charCode1 === 0){212 break213 }214 let str1 = ''215 if(charCode1 < 16){216 str1 = '%0' + charCode1.toString(16)217 }else{218 str1 = '%' + charCode1.toString(16)219 }220 i++221 const charCode2 = data.charCodeAt(i)222 if(charCode2 === 0){223 break224 }225 let str2 = ''226 if(charCode2 < 16){227 str2 = '%0' + charCode2.toString(16)228 }else{229 str2 = '%' + charCode2.toString(16)230 }231 escapeString += str1 + str2232 }233 return escapeString234 }235 /**236 *237 * @access private238 * @param {number[]} data - data to convert239 * @param {?string} [encoding = null] -240 * @returns {string} -241 */242 _convert(data, encoding) {243 let escapeString = ''244 if(encoding === 'utf16be'){245 escapeString = this._escapeBE(data)246 }else{247 escapeString = this._escapeLE(data)248 }249 250 if(encoding === 'sjis'){251 return UnescapeSJIS(escapeString)252 }else if(encoding === 'euc-jp'){253 return UnescapeEUCJP(escapeString)254 }else if(encoding === 'jis-7'){255 return UnescapeJIS7(escapeString)256 }else if(encoding === 'jis-8'){257 return UnescapeJIS8(escapeString)258 }else if(encoding === 'unicode'){259 return UnescapeUnicode(escapeString)260 }else if(encoding === 'utf7'){261 return UnescapeUTF7(escapeString)262 }else if(encoding === 'utf-8'){263 return UnescapeUTF8(escapeString)264 }else if(encoding === 'utf-16'){265 return UnescapeUTF16LE(escapeString)266 }else if(encoding === 'utf16be'){267 return UnescapeUTF16LE(escapeString)268 }269 throw new Error(`unsupported encoding: ${encoding}`)270 }271 getAvailableDataLength() {272 return this.buffer.length - this._pos273 }274 /**275 *276 * @access private277 * @param {number} len -278 * @returns {void}279 */280 _moveIndex(len) {281 this._partialText = this._partialText.substring(len)282 if(this._partialText.length < this._partialMinLength){283 this._addPartialText()284 }285 }286 _skipSpace() {287 let i = 0288 let code = this._partialText.charCodeAt(i)289 // 9: Horizontal Tab290 // 10: Line Feed291 // 11: Vertical Tab292 // 12: New Page293 // 13: Carriage Return294 // 32: Space295 while(code === 32 || (9 <= code && code <= 13)){296 i++297 code = this._partialText.charCodeAt(i)298 if(i >= this._partialText.length){299 this._addPartialText()300 }301 }302 if(i>0){303 this._moveIndex(i)304 }305 }306 _addPartialText() {307 if(this._partialOffset >= this.buffer.length){308 return309 }310 let newOffset = this._partialOffset + this._partialStep311 if(newOffset > this.buffer.length){312 newOffset = this.buffer.length313 }314 if(Buffer.isEncoding(this.encoding)){315 this._partialText += this.buffer.toString(this.encoding, this._partialOffset, newOffset)316 }else{317 const data = this.buffer.toString('binary', this._partialOffset, newOffset)318 this._partialText += this._convert(data, this.encoding)319 }320 this._partialOffset = newOffset321 }322 _getString(pattern) {323 this._skipSpace()324 const str = this._partialText.match(pattern)325 if(str === null){326 return null327 }328 this._moveIndex(str[0].length)329 return str330 }...

Full Screen

Full Screen

_BinaryReader.js

Source:_BinaryReader.js Github

copy

Full Screen

1'use strict'2import {3 UnescapeSJIS, UnescapeEUCJP, UnescapeJIS7, UnescapeJIS8, 4 UnescapeUnicode, UnescapeUTF7, UnescapeUTF8, UnescapeUTF16LE5} from '../third_party/ecl'6/*global Buffer*/7/**8 * BinaryReader class9 * @access public10 */11export default class _BinaryReader {12 /**13 * constructor14 * @param {Buffer|ArrayBuffer} data - 15 * @param {boolean} bigEndian -16 * @param {string} encoding -17 * @constructor18 */19 constructor(data, bigEndian = false, encoding = '') {20 /**21 * @access private22 * @type {number}23 */24 this._pos = 025 /**26 * @access private27 * @type {boolean}28 */29 this._eof = true30 /**31 *32 * @access public33 * @type {Buffer}34 */35 this.buffer = null36 if(data instanceof Buffer){37 this.buffer = data38 }else if(typeof data === 'string'){39 this.buffer = Buffer.from(data, 'binary')40 }else{41 this.buffer = Buffer.from(data)42 }43 /**44 *45 * @access public46 * @type {boolean}47 */48 this.bigEndian = bigEndian49 /**50 *51 * @access public52 * @type {string}53 */54 this.encoding = encoding55 }56 /**57 * @access public58 * @param {number} length - length of data to skip59 * @param {boolean} noAssert -60 * @returns {void}61 */62 skip(length, noAssert = false) {63 this._pos += length64 if(!noAssert){65 this._check()66 }67 }68 /**69 * @access public70 * @param {number} pos -71 * @returns {void}72 */73 seek(pos) {74 if(pos < 0){75 this._pos = this.buffer.length + pos76 }else{77 this._pos = pos78 }79 if(this._pos < 0){80 this._pos = 081 }else if(this._pos > this.buffer.length){82 this._pos = this.buffer.length83 }84 }85 /**86 *87 * @access public88 * @param {number} length - length of data to read89 * @param {?string} [encoding = null] -90 * @returns {string} -91 */92 readString(length, encoding = null) {93 const start = this._pos94 this._pos += length95 const _encoding = encoding || this.encoding || 'sjis'96 //if(_Buffer.isEncoding(_encoding)){97 if(Buffer.isEncoding(_encoding)){98 return this.buffer.toString(_encoding, start, this._pos)99 }100 const data = this.buffer.toString('binary', start, this._pos)101 return this._convert(data, _encoding)102 }103 /**104 *105 * @access public106 * @param {number} length - 107 * @param {boolean} signed -108 * @returns {number} -109 */110 readInteger(length, signed) {111 const start = this._pos112 this._pos += length113 // big endian114 if(this.bigEndian){115 if(signed){116 return this.buffer.readIntBE(start, length)117 }118 return this.buffer.readUIntBE(start, length)119 }120 // little endian121 if(signed){122 return this.buffer.readIntLE(start, length)123 }124 return this.buffer.readUIntLE(start, length)125 }126 /**127 *128 * @access public129 * @returns {number} -130 */131 readUnsignedByte() {132 return this.readInteger(1, false)133 }134 /**135 *136 * @access public137 * @returns {number} -138 */139 readUnsignedShort() {140 return this.readInteger(2, false)141 }142 /**143 *144 * @access public145 * @returns {number} -146 */147 readUnsignedInt() {148 return this.readInteger(4, false)149 }150 /**151 *152 * @access public153 * @returns {number} -154 */155 readUnsignedLongLong() {156 return this.readInteger(8, false)157 }158 /**159 *160 * @access public161 * @returns {number} -162 */163 readByte() {164 return this.readInteger(1, true)165 }166 /**167 *168 * @access public169 * @returns {number} -170 */171 readShort() {172 return this.readInteger(2, true)173 }174 /**175 *176 * @access public177 * @returns {number} -178 */179 readInt() {180 return this.readInteger(4, true)181 }182 /**183 *184 * @access public185 * @returns {number} -186 */187 readLongLong() {188 return this.readInteger(8, true)189 }190 /**191 *192 * @access public193 * @returns {number} -194 */195 readFloat() {196 const start = this._pos197 this._pos += 4198 if(this.bigEndian){199 return this.buffer.readFloatBE(start)200 }201 return this.buffer.readFloatLE(start)202 }203 /**204 *205 * @access public206 * @returns {number} -207 */208 readDouble() {209 const start = this._pos210 this._pos += 8211 if(this.bigEndian){212 return this.buffer.readDoubleBE(start)213 }214 return this.buffer.readDoubleLE(start)215 }216 /**217 *218 * @access public219 * @param {number} length -220 * @returns {Buffer} -221 */222 readData(length) {223 const start = this._pos224 this._pos += length225 return this.buffer.slice(start, this._pos)226 }227 /**228 *229 * @access private230 * @returns {void}231 */232 _check() {233 if(this._pos >= this.buffer.length){234 throw new Error(`_BinaryReader: buffer out of range (${this._pos} >= ${this.buffer.length})`)235 }236 }237 /**238 * 239 * @access private240 * @param {number[]} data - data to escape241 * @param {?string} [encoding = null] -242 * @returns {string} - escaped string243 */244 _escapeLE(data, encoding) {245 const length = data.length246 let escapeString = ''247 for(let i=0; i<length; i++){248 const charCode = data.charCodeAt(i)249 if(charCode === 0){250 break251 }252 else if(charCode < 16){253 escapeString += '%0' + charCode.toString(16)254 }else{255 escapeString += '%' + charCode.toString(16)256 }257 }258 return escapeString259 }260 /**261 * 262 * @access private263 * @param {number[]} data - data to escape264 * @param {?string} [encoding = null] -265 * @returns {string} - escaped string266 */267 _escapeBE(data, encoding) {268 const length = data.length269 let escapeString = ''270 for(let i=0; i<length; i++){271 const charCode1 = data.charCodeAt(i)272 if(charCode1 === 0){273 break274 }275 let str1 = ''276 if(charCode1 < 16){277 str1 = '%0' + charCode1.toString(16)278 }else{279 str1 = '%' + charCode1.toString(16)280 }281 i++282 const charCode2 = data.charCodeAt(i)283 if(charCode2 === 0){284 break285 }286 let str2 = ''287 if(charCode2 < 16){288 str2 = '%0' + charCode2.toString(16)289 }else{290 str2 = '%' + charCode2.toString(16)291 }292 escapeString += str1 + str2293 }294 return escapeString295 }296 /**297 *298 * @access private299 * @param {number[]} data - length of data to convert300 * @param {?string} [encoding = null] -301 * @returns {string} -302 */303 _convert(data, encoding) {304 let escapeString = ''305 if(encoding === 'utf16be'){306 escapeString = this._escapeBE(data)307 }else{308 escapeString = this._escapeLE(data)309 }310 311 if(encoding === 'sjis'){312 return UnescapeSJIS(escapeString)313 }else if(encoding === 'euc-jp'){314 return UnescapeEUCJP(escapeString)315 }else if(encoding === 'jis-7'){316 return UnescapeJIS7(escapeString)317 }else if(encoding === 'jis-8'){318 return UnescapeJIS8(escapeString)319 }else if(encoding === 'unicode'){320 return UnescapeUnicode(escapeString)321 }else if(encoding === 'utf7'){322 return UnescapeUTF7(escapeString)323 }else if(encoding === 'utf-8'){324 return UnescapeUTF8(escapeString)325 }else if(encoding === 'utf-16'){326 return UnescapeUTF16LE(escapeString)327 }else if(encoding === 'utf16be'){328 return UnescapeUTF16LE(escapeString)329 }330 throw new Error(`unsupported encoding: ${encoding}`)331 }332 getAvailableDataLength() {333 return this.buffer.length - this._pos334 }335 get length() {336 return this.buffer.length337 }...

Full Screen

Full Screen

appcontainer-driver.js

Source:appcontainer-driver.js Github

copy

Full Screen

...82/** Value, text, attributes, length ***/83/**************************************/84Element.prototype.val = function(str) {85 if(str != undefined) {86 window.frames['mslappcontainer'].eval('$("' + escapeString(this.locator) + '").val("' + escapeString(str) + '")');87 }else {88 return window.frames['mslappcontainer'].eval('$("' + escapeString(this.locator) + '").val()');89 }90}91Element.prototype.text = function() {92 return window.frames['mslappcontainer'].eval('$("' + escapeString(this.locator) + '").text()');93}94Element.prototype.attr = function(attributeName, value) {95 if(value != undefined) {96 window.frames['mslappcontainer'].eval('$("' + escapeString(this.locator) + '").attr("' + escapeString(attributeName) + '", "' + escapeString(value) + '")'); 97 }else {98 return window.frames['mslappcontainer'].eval('$("' + escapeString(this.locator) + '").attr("' + escapeString(attributeName) + '")'); 99 }100}101Element.prototype.size = function() {102 return window.frames['mslappcontainer'].eval('$("' + escapeString(this.locator) + '").size()');103}104/*********************/105/** Keyboard Events **/106/*********************/107Element.prototype.keydown = function() {108 window.frames['mslappcontainer'].eval('$("' + escapeString(this.locator) + '").keydown()');109}110Element.prototype.keypress = function() {111 window.frames['mslappcontainer'].eval('$("' + escapeString(this.locator) + '").keypress()');112}113Element.prototype.keyup = function() {114 window.frames['mslappcontainer'].eval('$("' + escapeString(this.locator) + '").keyup()');115}116/******************/117/** Mouse Events **/118/******************/119Element.prototype.click = function() {120 window.frames['mslappcontainer'].eval('$("' + escapeString(this.locator) + '").click()');121}122Element.prototype.dblclick = function() {123 window.frames['mslappcontainer'].eval('$("' + escapeString(this.locator) + '").dblclick()');124}125Element.prototype.focusout = function() {126 window.frames['mslappcontainer'].eval('$("' + escapeString(this.locator) + '").focusout()');127}128Element.prototype.hover = function() {129 window.frames['mslappcontainer'].eval('$("' + escapeString(this.locator) + '").hover()');130}131Element.prototype.mousedown = function() {132 window.frames['mslappcontainer'].eval('$("' + escapeString(this.locator) + '").mousedown()');133}134Element.prototype.mouseenter = function() {135 window.frames['mslappcontainer'].eval('$("' + escapeString(this.locator) + '").mouseenter()');136}137Element.prototype.mouseleave = function() {138 window.frames['mslappcontainer'].eval('$("' + escapeString(this.locator) + '").mouseleave()');139}140Element.prototype.mousemove = function() {141 window.frames['mslappcontainer'].eval('$("' + escapeString(this.locator) + '").mousemove()');142}143Element.prototype.mouseout = function() {144 window.frames['mslappcontainer'].eval('$("' + escapeString(this.locator) + '").mouseout()');145}146Element.prototype.mouseover = function() {147 window.frames['mslappcontainer'].eval('$("' + escapeString(this.locator) + '").mouseover()');148}149Element.prototype.mouseup = function() {150 window.frames['mslappcontainer'].eval('$("' + escapeString(this.locator) + '").mouseup()');151}152Element.prototype.toggle = function() {153 window.frames['mslappcontainer'].eval('$("' + escapeString(this.locator) + '").toggle()');154}155/**156 * Escapes single, double quotes, and backslashes of the given string.157 * @name escapeString158 * @param {string} str - string to escape159 * @returns {string} the escaped string160 */161function escapeString(str) {162 if(str === undefined) {163 throw new Error('\'str\' is required');164 }165 if(str === null) {166 throw new Error('\'str\' must not be null');167 }168 if(typeof str !== 'string') {169 throw new Error('\'str\' must be a string');170 }171 /*172 * Need to escape backslashes (\) first because escaping ' and " will also 173 * add a \, which interferes with \ escaping.174 */175 var escaped_str = str;...

Full Screen

Full Screen

appcontainerDriverSpec.js

Source:appcontainerDriverSpec.js Github

copy

Full Screen

1describe('appcontainer-driver', function() {2 3 describe('escapeString()', function() {4 it('escapes single quotes', function() {5 var escaped = escapeString("I'm using MSL");6 expect(escaped).toEqual("I\\'m using MSL");7 });8 it('escapes double quotes', function() {9 var escaped = escapeString('MSL stands for "Mock Service Layer"');10 expect(escaped).toEqual('MSL stands for \\"Mock Service Layer\\"');11 });12 it('escapes backslashes', function() {13 var escaped = escapeString('MSL now uses \\ to escape quotes');14 expect(escaped).toEqual('MSL now uses \\\\ to escape quotes');15 });16 it('escapes backslashes and quotes', function() {17 var escaped = escapeString('MSL now uses \\ to escape quotes, "this quote should be escaped"');18 expect(escaped).toEqual('MSL now uses \\\\ to escape quotes, \\"this quote should be escaped\\"');19 });20 it('does nothing if the string does not contain quotes or backslashes', function() {21 var escaped = escapeString('MSL is cool!');22 expect(escaped).toEqual('MSL is cool!');23 });24 it('throws if given no arguments', function() {25 expect(function() {26 escapeString();27 }).toThrow();28 });29 it('throws if given null argument', function() {30 expect(function() {31 escapeString(null);32 }).toThrow();33 });34 it('throws if given defined, non-null, non-string argument', function() {35 expect(function() {36 escapeString(0);37 }).toThrow();38 expect(function() {39 escapeString(1);40 }).toThrow();41 expect(function() {42 escapeString(-1);43 }).toThrow();44 expect(function() {45 escapeString(2);46 }).toThrow();47 expect(function() {48 escapeString(true);49 }).toThrow();50 expect(function() {51 escapeString(false);52 }).toThrow();53 expect(function() {54 escapeString([]);55 }).toThrow();56 expect(function() {57 escapeString([123]);58 }).toThrow();59 expect(function() {60 escapeString({});61 }).toThrow();62 expect(function() {63 escapeString({a:123});64 }).toThrow();65 });66 });67 ...

Full Screen

Full Screen

javascript-instrument.js

Source:javascript-instrument.js Github

copy

Full Screen

...15 onAttach: function onAttach(worker) {16 function processCallsAndValues(data) {17 var update = {};18 update["crawl_id"] = crawlID;19 update["script_url"] = loggingDB.escapeString(data.scriptUrl);20 update["script_line"] = loggingDB.escapeString(data.scriptLine);21 update["script_col"] = loggingDB.escapeString(data.scriptCol);22 update["func_name"] = loggingDB.escapeString(data.funcName);23 update["script_loc_eval"] = loggingDB.escapeString(data.scriptLocEval);24 update["call_stack"] = loggingDB.escapeString(data.callStack);25 update["symbol"] = loggingDB.escapeString(data.symbol);26 update["operation"] = loggingDB.escapeString(data.operation);27 update["value"] = loggingDB.escapeString(data.value);28 update["time_stamp"] = data.timeStamp;2930 // document_url is the current frame's document href31 // top_level_url is the top-level frame's document href32 update["document_url"] = loggingDB.escapeString(worker.url);33 update["top_level_url"] = loggingDB.escapeString(worker.tab.url);3435 // Create a json object for function arguments36 // We create an object that maps array positon to argument37 // e.g. someFunc('a',123,'b') --> {0: a, 1: 123, 2: 'b'}38 // to make it easier to query the data, using something like the39 // sqlite3 json1 extension.40 var args = {};41 if (data.operation == 'call' && data.args.length > 0) {42 for(var i = 0; i < data.args.length; i++) {43 args[i] = data.args[i]44 }45 update["arguments"] = loggingDB.escapeString(JSON.stringify(args));46 }4748 loggingDB.saveRecord("javascript", update);49 }50 worker.port.on("logCall", function(data){processCallsAndValues(data)});51 worker.port.on("logValue", function(data){processCallsAndValues(data)});52 }53 }); ...

Full Screen

Full Screen

reg_exp_spec.js

Source:reg_exp_spec.js Github

copy

Full Screen

1require('../../support/spec_helper');2describe("Cucumber.Util.RegExp", function () {3 var Cucumber = requireLib('cucumber');4 describe("escapeString()", function () {5 var escapeString = Cucumber.Util.RegExp.escapeString;6 it("escapes dashes", function () {7 expect(escapeString("-")).toBe("\\-");8 });9 it("escapes square brackets", function () {10 expect(escapeString("[]")).toBe("\\[\\]");11 });12 it("escapes curly brackets", function () {13 expect(escapeString("{}")).toBe("\\{\\}");14 });15 it("escapes parentheses", function () {16 expect(escapeString("()")).toBe("\\(\\)");17 });18 it("escapes asterisks", function () {19 expect(escapeString("*")).toBe("\\*");20 });21 it("escapes plusses", function () {22 expect(escapeString("+")).toBe("\\+");23 });24 it("escapes question marks", function () {25 expect(escapeString("?")).toBe("\\?");26 });27 it("escapes dots", function () {28 expect(escapeString(".")).toBe("\\.");29 });30 it("escapes backslashes", function () {31 expect(escapeString("\\")).toBe("\\\\");32 });33 it("escapes carets", function () {34 expect(escapeString("^")).toBe("\\^");35 });36 it("escapes dollar signs", function () {37 expect(escapeString("$")).toBe("\\$");38 });39 it("escapes pipes", function () {40 expect(escapeString("|")).toBe("\\|");41 });42 it("escapes hashes", function () {43 expect(escapeString("#")).toBe("\\#");44 });45 it("escapes new lines", function () {46 expect(escapeString("\n")).toBe("\\\n");47 });48 it("escapes forward slashes", function () {49 expect(escapeString("/")).toBe("\\/");50 });51 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var tracetest = require('tracetest');2var str = tracetest.escapeString("Hello World");3console.log(str);4exports.escapeString = function(str) {5 return str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");6};

Full Screen

Using AI Code Generation

copy

Full Screen

1var tracetest = require('tracetest');2var string = "This is a test string";3var escapedString = tracetest.escapeString(string);4console.log("Escaped string: " + escapedString);5var unescapedString = tracetest.unescapeString(escapedString);6console.log("Unescaped string: " + unescapedString);

Full Screen

Using AI Code Generation

copy

Full Screen

1var tracetest = require('tracetest');2var str = "This is a test";3var result = tracetest.escapeString(str);4console.log(result);5var escapeString = function(str){6 return str.replace(/[^a-zA-Z0-9]/g,"_");7};8exports.escapeString = escapeString;9I am using the require() method to import the tracetest module in test.js. I am using the exports object to export the escapeString method in tracetest.js. I

Full Screen

Using AI Code Generation

copy

Full Screen

1var tracetesting = require('tracetesting');2var inputString = "This is a test string";3var outputString = tracetesting.escapeString(inputString);4console.log(outputString);5var tracetesting = require('tracetesting');6var inputString = "This is a test string";7var outputString = tracetesting.escapeString(inputString);8console.log(outputString);9var tracetesting = require('tracetesting');10var inputString = "This is a test string";11var outputString = tracetesting.escapeString(inputString);12console.log(outputString);13var tracetesting = require('tracetesting');14var inputString = "This is a test string";15var outputString = tracetesting.escapeString(inputString);16console.log(outputString);17var tracetesting = require('tracetesting');18var inputString = "This is a test string";19var outputString = tracetesting.escapeString(inputString);20console.log(outputString);21var tracetesting = require('tracetesting');22var inputString = "This is a test string";23var outputString = tracetesting.escapeString(inputString);24console.log(outputString);25var tracetesting = require('tracetesting');26var inputString = "This is a test string";27var outputString = tracetesting.escapeString(inputString);28console.log(outputString);29var tracetesting = require('tracetesting');30var inputString = "This is a test string";31var outputString = tracetesting.escapeString(inputString);32console.log(outputString);

Full Screen

Using AI Code Generation

copy

Full Screen

1var tracetest = require('./tracetest');2var trace = new tracetest();3var s = "This is a test";4console.log(trace.escapeString(s));5var tracetest = function() {6 return {7 escapeString: function(s) {8 return s.replace(/ /g, '%20');9 }10 }11}12module.exports = tracetest;13Related Posts: Node.js - How to use require() method?14Node.js - How to use console.log() method?15Node.js - How to use setTimeout() method?16Node.js - How to use setInterval() method?17Node.js - How to use clearTimeout() method?18Node.js - How to use clearInterval() method?19Node.js - How to use unescape() method?20Node.js - How to use escape() method?21Node.js - How to use unescape() method?22Node.js - How to use escape() method?23Node.js - How to use unescape() method?24Node.js - How to use escape() method?25Node.js - How to use unescape() method?26Node.js - How to use escape() method?27Node.js - How to use unescape() method?28Node.js - How to use escape() method?29Node.js - How to use unescape() method?30Node.js - How to use escape() method?31Node.js - How to use unescape() method?32Node.js - How to use escape() method?

Full Screen

Using AI Code Generation

copy

Full Screen

1var traceTest = require('./tracetest').traceTest;2var tracetest = new traceTest();3var str = "Hello 'World'";4console.log(tracetest.escapeString(str));5exports.traceTest = function() {6 this.escapeString = function(str) {7 return str.replace(/'/g, '\\\'');8 };9};10Thanks for your reply. But I'm not sure if I understand you correctly. I thought I could use the escapeString function from the tracetest.js file in the test.js file. The problem is that it is not visible in the test.js file. So I think I have to export the function from the tracetest.js file. So I added the exports.traceTest = function() { ... } line in the tracetest.js file. But I still get the error message that escapeString is not defined. I'm not sure if I'm doing it correctly. Can you give me an example?11So I think I have to export the function from the tracetest.js file. So I added the exports.traceTest = function() { ... } line in the tracetest.js file. But I still get the error message that escapeString is not defined. I'm not sure if I'm doing it correctly. Can you give me an example?

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run tracetest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful