Best JavaScript code snippet using best
uploader.js
Source: uploader.js
...48 let imgUrl = commonUtil.htmlspecialchars(this.fileField);49 imgUrl = imgUrl.replace("&", "&", imgUrl);50 //http å¼å¤´éªè¯51 if(imgUrl.indexOf("http") !== 0) {52 this.stateInfo = this.getStateInfo("ERROR_HTTP_LINK");53 return;54 }55 request(imgUrl, function(err, res, body) {56 if(err || (res.statusCode !== 20057 && res.statusCode !== 304)) {58 this.stateInfo = this.getStateInfo("ERROR_DEAD_LINK");59 return;60 }61 let fileName = imgUrl.substr(imgUrl.lastIndexOf(think.sep) + 1);62 let fileType = fileName.substr(fileName.lastIndexOf(".") + 1);63 if(this.config.allowFiles.indexOf(fileType) === -1) {64 this.stateInfo = this.getStateInfo("ERROR_HTTP_CONTENTTYPE");65 return;66 }67 let matches = imgUrl.match(/[\/]([^\/]*)[\.]?[^\.\/]*$/);68 this.oriName = matches ? matches[1] : "";69 this.fileSize = body.length;70 this.fileType = this.getFileExt() || fileType;71 this.fullName = this.getFullName();72 this.filePath =this.getFilePath();73 this.fileName = this.getFileName();74 let dirname = path.dirname(this.filePath);75 //æ£æ¥æ件大å°æ¯å¦è¶
åºéå¶76 if(!this.checkSize()) {77 this.stateInfo = this.getStateInfo("ERROR_SIZE_EXCEED");78 return;79 }80 //æ£æ¥æ¯å¦ä¸å
许çæä»¶æ ¼å¼81 if(!this.checkType()) {82 this.stateInfo = this.getStateInfo("ERROR_TYPE_NOT_ALLOWED");83 return;84 }85 //å建ç®å½å¤±è´¥86 if(!fs.existsSync(dirname) && !think.mkdir(dirname)) {87 this.stateInfo = this.getStateInfo("ERROR_CREATE_DIR");88 return;89 } else if (!think.isWritable(dirname)) {90 this.stateInfo = this.getStateInfo("ERROR_DIR_NOT_WRITEABLE");91 return;92 }93 //移å¨æ件94 if(!fs.existsSync(this.filePath)) {95 think.mkdir(this.filePath);96 }97 try {98 fs.writeFileSync(this.filePath, imgBuf);99 } catch(e) {100 this.stateInfo = this.getStateInfo("ERROR_FILE_MOVE");101 return;102 }103 this.stateInfo = this.getStateInfo("SUCCESS_FILE_MOVE");104 })105 }106 upBase64() {107 let base64Data = thinkjs.post(this.fileField);108 let imgBuf = new Buffer(base64Data, 'base64');109 this.oriName = this.config.oriName;110 this.fileSize = imgBuf.length;111 this.fileType = this.getFileExt();112 this.fullName = this.getFullName();113 this.filePath = this.getFilePath();114 115 let dirname = path.dirname(this.filePath);116 //æ£æ¥æ件大å°æ¯å¦è¶
åºéå¶117 if(!this.checkSize()) {118 this.stateInfo = this.getStateInfo("ERROR_SIZE_EXCEED");119 return;120 }121 //æ£æ¥æ¯å¦ä¸å
许çæä»¶æ ¼å¼122 if(!this.checkType()) {123 this.stateInfo = this.getStateInfo("ERROR_TYPE_NOT_ALLOWED");124 return;125 }126 //å建ç®å½å¤±è´¥127 if(!fs.existsSync(dirname) && !think.mkdir(dirname)) {128 this.stateInfo = this.getStateInfo("ERROR_CREATE_DIR");129 return;130 } else if (!think.isWritable(dirname)) {131 this.stateInfo = this.getStateInfo("ERROR_DIR_NOT_WRITEABLE");132 return;133 }134 //移å¨æ件135 if(!fs.existsSync(this.filePath)) {136 think.mkdir(this.filePath);137 }138 try {139 fs.writeFileSync(this.filePath, imgBuf);140 } catch(e) {141 this.stateInfo = this.getStateInfo("ERROR_FILE_MOVE");142 return;143 }144 this.stateInfo = this.getStateInfo("SUCCESS_FILE_MOVE");145 }146 upFile() {147 let file = this.file = this.thinkjs.file(this.fileField);148 if(!file) {149 this.stateInfo = this.getStateInfo("ERROR_FILE_NOT_FOUND");150 return;151 }152 //æ件é误æ¶å¤ç,æªæµè¯è¿æ¯å¦æ£å¸¸ä½¿ç¨153 if(!this.file.originalFilename) {154 this.stateInfo = this.getStateInfo("EMPTY_FILE");155 return;156 } else if(!fs.existsSync(file.path)) {157 this.stateInfo = this.getStateInfo("ERROR_TMP_FILE_NOT_FOUND");158 return;159 }160 this.oriName = file.originalFilename;161 this.fileSize = file.size;162 this.fileType = this.getFileExt();163 this.fullName = this.getFullName();164 this.filePath = this.getFilePath();165 166 let dirname = path.dirname(this.filePath);167 //æ£æ¥æ件大å°æ¯å¦è¶
åºéå¶168 if(!this.checkSize()) {169 this.stateInfo = this.getStateInfo("ERROR_SIZE_EXCEED");170 return;171 }172 //æ£æ¥æ¯å¦ä¸å
许çæä»¶æ ¼å¼173 if(!this.checkType()) {174 this.stateInfo = this.getStateInfo("ERROR_TYPE_NOT_ALLOWED");175 return;176 }177 //å建ç®å½å¤±è´¥178 if(!fs.existsSync(dirname) && !think.mkdir(dirname)) {179 this.stateInfo = this.getStateInfo("ERROR_CREATE_DIR");180 return;181 } else if (!think.isWritable(dirname)) {182 this.stateInfo = this.getStateInfo("ERROR_DIR_NOT_WRITEABLE");183 return;184 }185 //移å¨æ件186 let buf = fs.readFileSync(this.file.path);187 try {188 fs.writeFileSync(this.filePath, buf);189 } catch(e) {190 this.stateInfo = this.getStateInfo("ERROR_FILE_MOVE");191 return;192 }193 this.stateInfo = this.getStateInfo("SUCCESS_FILE_MOVE");194 }195 getFileExt() {196 if(!this.file) return this.config.ext;197 let oName = this.file.originalFilename;198 let idx = oName.lastIndexOf(".");199 let ext = idx >= 0 ? oName.substr(idx + 1) : '';200 return (ext || this.config.ext).toLowerCase();201 }202 getFullName() {203 let oriName = this.config.oriName;204 oriName = oriName.substr(0, oriName.lastIndexOf("."));205 oriName = oriName.replace(/[\|\?\"\<\>\/\*\\\\]+/, "");206 let date = moment().format("YYYY-YY-MM-DD-hh-mm-ss").split("-");207 let format = this.config.imagePathFormat.toLowerCase();208 format = format.replace("{yyyy}", date[0])209 .replace("{yy}", date[1])210 .replace("{mm}", date[2])211 .replace("{dd}", date[3])212 .replace("{hh}", date[4])213 .replace("{ii}", date[5])214 .replace("{ss}", date[6])215 .replace("{time}", Date.now())216 .replace("{filename}", oriName);217 let randNum = Math.random() * 10000000000 + "" + Math.random() * 10000000000;218 let matches;219 if((matches = format.match(/\{rand\:([\d]*)\}/i))) {220 format = format.replace(/\{rand\:[\d]*\}/i, randNum.substr(0, matches[1]));221 }222 //é¢å¤å»é¤phpåç¼223 format = format.replace("php/", "");224 return format + "." + this.getFileExt();225 }226 getFilePath() {227 let fullName = this.fullName;228 let rootPath = think.ROOT_PATH;229 return path.normalize(rootPath + "/www/" + fullName);230 }231 getFileName() {232 return this.filePath.substr(this.filePath.lastIndexOf("/") + 1);233 }234 checkSize() {235 return this.fileSize <= this.config.maxSize;236 }237 checkType() {238 if(!this.config.allowFiles) return true;239 let type = Object.prototype.toString.call(this.config.allowFiles)240 .split(' ')[1].replace("]", "");241 if(type === 'Array') {242 return this.config.allowFiles243 .indexOf(this.getFileExt()) != -1;244 } else if(type === "String") {245 return this.config.allowFiles.split(",")246 .indexOf(this.getFileExt()) != -1;247 } else {248 return false;249 }250 }251 /**252 * ä¸ä¼ é误æ£æ¥253 * @param errCode254 * @return string255 */256 getStateInfo(errCode)257 {258 return this.stateMap[errCode] || this.stateMap["ERROR_UNKNOWN"];259 }260 /**261 * è·åå½åä¸ä¼ æåæ件çå项信æ¯262 * @return array263 */264 getFileInfo() {265 return {266 "state": this.stateInfo,267 "url": this.fullName,268 "title": this.fileName,269 "original": this.oriName,270 "type": this.fileType,...
get_state_promise.js
Source: get_state_promise.js
1const request = require('request')2// http://services.groupkt.com/state/get/IND/JK3function getStateInfo(country, state) {4 return new Promise( (resolve, reject) => {5 request(`http://services.groupkt.com/state/get/${country}/${state}`, (err, res, body) => {6 if(err) {7 reject('error occured while fetching country\'s state info');8 }9 else if(res.statusCode === 200) {10 //console.log(JSON.stringify(body, undefined, 8));11 resolve(JSON.parse(body).RestResponse.result.capital);12 }13 })14 });15}...
getStateInfo.js
Source: getStateInfo.js
1const request = require('request')2// http://services.groupkt.com/state/get/IND/JK3function getStateInfo(country, state, callback) {4 request(`http://services.groupkt.com/state/get/${country}/${state}`, (err, res, body) => {5 if(err) {6 callback('error occured while fetching country\'s state info');7 }8 else if(res.statusCode === 200) {9 //console.log(JSON.stringify(body, undefined, 8));10 callback(null, JSON.parse(body).RestResponse.result.capital);11 }12 })13}...
Using AI Code Generation
1var request = require('request');2request(url, function (error, response, body) {3 if (!error && response.statusCode == 200) {4 }5});6var request = require('request');7request(url, function (error, response, body) {8 if (!error && response.statusCode == 200) {9 }10});11var request = require('request');12request(url, function (error, response, body) {13 if (!error && response.statusCode == 200) {14 }15});16var request = require('request');17request(url, function (error, response, body) {18 if (!error && response.statusCode == 200) {19 }20});21var request = require('request');
Using AI Code Generation
1var bestBuy = require('./bestBuy.js');2var bb = new bestBuy();3bb.getStateInfo('CA', function(err, result){4 if(err) {5 console.log(err);6 }7 else {8 console.log(result);9 }10});11{ storeType: 'Big Box',12 state: 'CA' }13var bestBuy = require('./bestBuy.js');14var bb = new bestBuy();15bb.getStores('CA', function(err, result){16 if(err) {17 console.log(err);18 }19 else {20 console.log(result);21 }22});23{ stores:24 [ { city: 'Alameda',25 'Mon-Sat: 9:00 AM - 9:00 PM; Sun: 10:00 AM - 8:00 PM',26 state: 'CA' },27 { city: 'Anaheim',28 'Mon-Sat: 9:00 AM - 9:00 PM; Sun: 10:00 AM - 8:00 PM',29 state: 'CA' },30 { city: 'Antioch',
Using AI Code Generation
1var storeLocator = require('bestbuy-store-locator');2var store = new storeLocator.BestBuyStoreLocator();3store.getStateInfo('MN','Mall of America',function(err, data){4 console.log(data);5});6var storeLocator = require('bestbuy-store-locator');7var store = new storeLocator.BestBuyStoreLocator();8store.getStoreInfo('MN','Mall of America',function(err, data){9 console.log(data);10});11var storeLocator = require('bestbuy-store-locator');12var store = new storeLocator.BestBuyStoreLocator();13store.getStoreByState('MN',function(err, data){14 console.log(data);15});16var storeLocator = require('bestbuy-store-locator');17var store = new storeLocator.BestBuyStoreLocator();18store.getStoreByZip('55401',function(err, data){19 console.log(data);20});21var storeLocator = require('bestbuy-store-locator');22var store = new storeLocator.BestBuyStoreLocator();23store.getStoreByCity('Saint Paul',function(err, data){24 console.log(data);25});26var storeLocator = require('bestbuy-store-locator');27var store = new storeLocator.BestBuyStoreLocator();28store.getStoreByArea('55401',function(err, data){29 console.log(data);30});31var storeLocator = require('bestbuy-store-locator');
Using AI Code Generation
1var BestBuy = require('./BestBuy');2var stateCode = process.argv[2];3BestBuy.getStateInfo(stateCode, function(stateInfo){4console.log(stateInfo);5});6var BestBuy = require('./BestBuy');7var storeId = process.argv[2];8BestBuy.getStoreInfo(storeId, function(storeInfo){9console.log(storeInfo);10});11var BestBuy = require('./BestBuy');12var stateCode = process.argv[2];13BestBuy.getStoresInState(stateCode, function(storesInState){14console.log(storesInState);15});16var BestBuy = require('./BestBuy');17var zipCode = process.argv[2];18BestBuy.getStoresInZip(zipCode, function(storesInZip){19console.log(storesInZip);20});21var BestBuy = require('./BestBuy');22var cityName = process.argv[2];23BestBuy.getStoresInCity(cityName, function(storesInCity){24console.log(storesInCity);25});26var BestBuy = require('./BestBuy');27var areaName = process.argv[2];28BestBuy.getStoresInArea(areaName, function(storesInArea){29console.log(stores
Using AI Code Generation
1var http = require('http');2function getStateName(stateAbbreviation, callback) {3 var options = {4 path: '/v1/stores(area(' + stateAbbreviation + ',25))?format=json&show=longName,city&apiKey=8z7e5t5f5z5j5m5qf3q3u3v3'5 };6 var callback = function (response) {7 var str = '';8 response.on('data', function (chunk) {9 str += chunk;10 });11 response.on('end', function () {12 var obj = JSON.parse(str);13 var stateName = obj.stores[0].longName;14 console.log(stateName);15 });16 }17 http.request(options, callback).end();18}19getStateName('MN', function (stateName) {20 console.log(stateName);21});
Check out the latest blogs from LambdaTest on this topic:
LambdaTest has recently received two notable awards from the leading business software directory FinancesOnline after their experts were impressed with our test platform’s capabilities in accelerating one’s development process.
The layout of a web page is one of the most important features of a web page. It can affect the traffic inflow by a significant margin. At times, a designer may come up with numerous layout ideas and sometimes he/she may struggle the entire day to come up with one. Moreover, design becomes even more important when it comes to ensuring cross browser compatibility.
Chrome is hands down the most used browsers by developers and users alike. It is the primary reason why there is such a solid chrome community and why there is a huge list of Chrome Extensions targeted at developers.
In a startup, the major strength of the people is that they are multitaskers. Be it anything, the founders and the core team wears multiple hats and takes complete responsibilities to get the ball rolling. From designing to deploying, from development to testing, everything takes place under the hawk eyes of founders and the core members.
We are in the era of the ‘Heads down’ generation. Ever wondered how much time you spend on your smartphone? Well, let us give you an estimate. With over 2.5 billion smartphone users, an average human spends approximately 2 Hours 51 minutes on their phone every day as per ComScore’s 2017 report. The number increases by an hour if we include the tab users as well!
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!!