var save = function () { fs.writeFile(moment().format('LL') + '.txt', JSON.stringify(db), function (err) { if (err) throw err; console.log('Analytics saved to file ' + moment().format('LL') + '.txt'); }); };
var saveWindowBounds = function () { if (mainWindow) { fs.writeFile(appDataPath + 'windowBounds.json', JSON.stringify(mainWindow.getBounds())) } }
if (!ex) prompt(function (vars) { fs.writeFile(file, JSON.stringify(vars), function (err) { if (err) console.error(err) else read() }); })
'index.html:write': ['index.html:read', function(callback, results) { var content = results['index.html:read'].toString().replace('%URL%', url); fs.writeFile(INDEX_HTML, content, callback); }],
return fs.readFile(this.path, function (err, data) { fs.writeFile(path.join((this.path = tmpPath), 'index' + this.assetType), data, function () { this.once('loadJSON', this.saveUnit).loadJSON(); }.bind(this)); }.bind(this));
/* * 根据一个文件的全路径(如:/xxx/yyy/aa.js)从本地文件系统获取内容 */ function readFromLocal (fullPath) { fullPath = fullPath.split('?')[0]; var longestMatchPos = longgestMatchedDir(fullPath); if(!longestMatchPos){ return null } //找到最长匹配的配置,顺序遍历已定义好的目录。多个目录用逗号","分隔。 var map = param.urls; var dirs = map[longestMatchPos].split(','); for (var i = 0, len = dirs.length; i < len; i++) { var dir = dirs[i]; var revPath = path.join('/', fullPath.slice(longestMatchPos.length, fullPath.length)); var absPath = ''; debug('The rev path is %s', revPath); //如果是绝对路径,直接使用 if(dir.indexOf('/') === 0 || /^\w{1}:\\.*$/.test(dir)){ absPath = path.normalize(path.join(dir, revPath)); } else{ absPath = path.normalize(path.join(param.prjDir, dir, revPath)); } //前后端模板一致化,如果是*.html.js格式的请求,并且js文件不存在,则编译*.html为juicer的function格式返回 var extName = path.extname(absPath); var htmlName = absPath.slice(0, absPath.length - extName.length); if(path.extname(htmlName).toLowerCase() === '.html' && fs.existsSync(htmlName)){ var buff = fs.readFileSync(htmlName); var charset = isUtf8(buff) ? 'utf8' : 'gbk'; var tpl = iconv.decode(buff, charset); try { var compiled = juicer(tpl)._render.toString().replace(/^function anonymous[^{]*?{([\s\S]*?)}$/igm, function($, fn_body) { return 'function(_, _method) {' + method_body + fn_body + '};\n'; }); } catch(e) { cosoleResp('Error', 'Compile failed with error '+ e.message); return ''; } //允许为某个url特别指定编码 var outputCharset = param.charset; if(param.urlBasedCharset && param.urlBasedCharset[longestMatchPos]){ outputCharset = param.urlBasedCharset[longestMatchPos]; } var tempalteFunction; param.define = param.define || ''; // 未声明需要哪个定义模块 // 或者声明的错误 // 或者声明的是 `window` if ( !param.define || 'string' !== typeof param.define || !!~['window', 'global', 'self', 'parent','Window','Global'].indexOf(param.define) ) { debug('The package define is undefined or not a string'); tempalteFunction = 'window["'+revPath+'"] = ' + compiled; } else { if (param.anonymous) { debug('Define a anonymous module'); tempalteFunction = param.define + '(function(){return ' + compiled + '});'; } else { debug('Define a module with id'); tempalteFunction = param.define + '("' + revPath + '", function () {return ' + compiled + '});'; } } cosoleResp('Local Juicer Compile', htmlName); fs.writeFile(absPath, tempalteFunction); return iconv.encode(tempalteFunction, outputCharset); } // added by jayli // 新增less文件解析 less.css => .less if(/\.less\.css$/i.test(absPath) && !fs.existsSync(absPath) && fs.existsSync(absPath.replace(/\.css$/i,''))){ var buff = fs.readFileSync(absPath.replace(/\.css$/i,'')); var charset = isUtf8(buff) ? 'utf8' : 'gbk'; var fContent = iconv.decode(buff, charset); return new(less.Parser)({ processImports:false }).parse(fContent,function(e,tree){ return tree.toCSS(); }); } // scss文件解析 scss.css => scss if(/\.scss\.css$/i.test(absPath) && !fs.existsSync(absPath) && fs.existsSync(absPath.replace(/\.css$/i,''))){ var r_css = sass.renderSync({ file: absPath.replace(/\.css$/i,''), success: function (css, map) { } }); return r_css; } // .css => .less if(/\.css$/i.test(absPath) && !fs.existsSync(absPath) && fs.existsSync(absPath.replace(/\.css$/i,'.less'))){ var buff = fs.readFileSync(absPath.replace(/\.css$/i,'.less')); var charset = isUtf8(buff) ? 'utf8' : 'gbk'; var fContent = iconv.decode(buff, charset); return new(less.Parser)({ processImports:false }).parse(fContent,function(e,tree){ return tree.toCSS(); }); } // .css => .scss if(/\.css$/i.test(absPath) && !fs.existsSync(absPath) && fs.existsSync(absPath.replace(/\.css$/i,'.scss'))){ var r_css = sass.renderSync({ file: absPath.replace(/\.css$/i,'.scss'), success: function (css, map) { } }); return r_css; } if(fs.existsSync(absPath)){ var buff = fs.readFileSync(absPath); if(isBinFile(absPath)){ cosoleResp('Local', absPath); return buff; } var charset = isUtf8(buff) ? 'utf8' : 'gbk'; //允许为某个url特别指定编码 var outputCharset = param.charset; if(param.urlBasedCharset && param.urlBasedCharset[longestMatchPos]){ outputCharset = param.urlBasedCharset[longestMatchPos]; } cosoleResp('Local', absPath); return adaptCharset(buff, outputCharset, charset); } } return null; }
save: function (filename, ts, cb) { fs.writeFile(filename, ts.getContent(), 'binary', cb); },
return new Promise(function(res, rej) { fs.writeFile(self.entryPath, 'require("fs")', function(e) { if (e) throw e; res(); }); }).catch(function(e) {
write: function (filename, data, callback) { fs.writeFile(filename, data, function (err) { callback(err); }); },
return new Promise((res, rej) => { node_fs.writeFile(f, data, opts, (err) => { if (err) { rej(err); } else { res(); } }); });
var onClose = function(e) { fs.writeFile("output/search/" + type + ".json", data, function(err) { if (err) throw err; console.log('Done searching for ' + type); }); }
.then(function(data) { util.createResponse(200, data, res, 1); fs.writeFile('cached.json', JSON.stringify(data, null, 2), { flag: 'w' }); });
.then(function(data) { fs.writeFile('cached.json', JSON.stringify(data, null, 2), { flag: 'w' }); });
'use strict'; var swig = require('swig'); var fs = require('fs'); fs.writeFile('resultAssignedActivity.tex', swig.renderFile('assignedActivity.tex', { semesters: { spring: { teaching: 45, research: 40, service: 15 }, summer: { teaching: 45, research: 40, service: 15 }, fall: { teaching: 45, research: 40, service: 15 } } }), function(err) { if (err) throw err; console.log('Saved!'); });
function writeShop() { if (!writeJSON) return false; //Prevent corruptions fs.writeFile('config/Shop.json', JSON.stringify(Shop)); }
'use strict'; // file save sample // https://docs.nodejitsu.com/articles/file-system/how-to-write-files-in-nodejs var fs = require('fs'); fs.writeFile('logfile.log', 'hogehoge\nfugafuga\n', function(err){ if(err) throw err; console.log('saved'); });
"use strict";var urlParser=require("url");var http=require("http");var https=require("https");var util=require("util");var path=require("path");var fs=require("fs");var events=require("events");var crypto=require("crypto");var expressionCache={};var regexpMail=new RegExp("^[a-zA-Z0-9-_.]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$");var regexpUrl=new RegExp("^(http[s]?:\\/\\/(www\\.)?|ftp:\\/\\/(www\\.)?|www\\.){1}([0-9A-Za-z-\\.@:%_+~#=]+)+((\\.[a-zA-Z]{2,3})+)(/(.)*)?(\\?(.)*)?");var ENCODING="utf8";var UNDEFINED="undefined";var STRING="string";var FUNCTION="function";var NUMBER="number";var OBJECT="object";var BOOLEAN="boolean";var NEWLINE="\r\n";var VERSION=typeof framework!==UNDEFINED?"v"+framework.version:"";if(typeof setImmediate===UNDEFINED){global.setImmediate=function(cb){process.nextTick(cb)}}var hasOwnProperty=Object.prototype.hasOwnProperty;function expression(query,params){var name=params.join(",");var fn=expressionCache[query+"-"+name];if(!fn){fn=eval("(function("+name+"){"+(query.indexOf("return")===-1?"return ":"")+query+"})");expressionCache[query+name]=fn}var values=[];for(var i=2;i<arguments.length;i++)values.push(arguments[i]);return function(){var arr=[];for(var i=0;i<arguments.length;i++)arr.push(arguments[i]);for(var i=0;i<values.length;i++)arr.push(values[i]);return fn.apply(this,arr)}}global.expression=expression;exports.isEmpty=function(obj){if(obj===null)return true;if(obj.length&&obj.length>0)return false;if(obj.length===0)return true;for(var key in obj){if(hasOwnProperty.call(obj,key))return false}return true};exports.request=function(url,method,data,callback,headers,encoding,timeout){var uri=urlParser.parse(url);var h={};var isJSON=typeof data===OBJECT;encoding=encoding||ENCODING;method=(method||"").toString().toUpperCase();if(method!=="GET")h["Content-Type"]="application/x-www-form-urlencoded";if(isJSON)h["Content-Type"]="application/json";util._extend(h,headers);h["X-Powered-By"]="partial.js"+VERSION;var options={protocol:uri.protocol,auth:uri.auth,method:method,hostname:uri.hostname,port:uri.port,path:uri.path,agent:false,headers:h};var response=function(res){if(!callback){res.resume();return}res._buffer="";res.on("data",function(chunk){this._buffer+=chunk.toString(encoding)});res.on("end",function(){callback(null,this._buffer,res.statusCode,res.headers)});res.resume()};var con=options.protocol==="https:"?https:http;try{var isPOST=method==="POST"||method==="PUT";var req=isPOST?callback?con.request(options,response):con.request(options):callback?con.get(options,response):con.get(options);if(callback){req.on("error",function(error){callback(error,null,0,{})});req.setTimeout(timeout||1e4,function(){callback(new Error(exports.httpStatus(408)),null,0,{})})}if(isPOST)req.end(isJSON?JSON.stringify(data):(data||"").toString(),encoding)}catch(ex){if(callback)callback(ex,null,0,{});return false}return true};exports.download=function(url,callback,headers,method,params,encoding){var uri=urlParser.parse(url);var h={};method=(method||"").toString().toUpperCase();encoding=encoding||ENCODING;util._extend(h,headers);h["X-Powered-By"]="partial.js"+VERSION;var options={protocol:uri.protocol,auth:uri.auth,method:method,hostname:uri.hostname,port:uri.port,path:uri.path,agent:false,headers:h};var response=function(res){callback(null,res)};var con=options.protocol==="https:"?https:http;try{var isPOST=method==="POST"||method==="PUT";var req=isPOST?callback?con.request(options,response):con.request(options):callback?con.get(options,response):con.get(options);if(callback){req.on("error",function(error){callback(error,null)})}if(isPOST)req.end((params||"").toString(),ENCODING)}catch(ex){if(callback)callback(ex,null);return false}return true};exports.send=function(name,stream,url,callback,headers,method){var self=this;if(typeof callback==="object"){var tmp=headers;callback=headers;headers=tmp}if(typeof stream===STRING)stream=fs.createReadStream(stream,{flags:"r"});var BOUNDARY="----"+Math.random().toString(16).substring(2);var h={};if(headers)util._extend(h,headers);name=path.basename(name);h["Cache-Control"]="max-age=0";h["Content-Type"]="multipart/form-data; boundary="+BOUNDARY;h["X-Powered-By"]="partial.js"+VERSION;var uri=urlParser.parse(url);var options={protocol:uri.protocol,auth:uri.auth,method:method||"POST",hostname:uri.hostname,port:uri.port,path:uri.path,agent:false,headers:h};var response=function(res){if(!callback)return;res.body="";res.on("data",function(chunk){this.body+=chunk.toString(ENCODING)});res.on("end",function(){callback(null,res.body)})};var connection=options.protocol==="https:"?https:http;var req=connection.request(options,response);if(callback){req.on("error",function(err){callback(err,null)})}var header=NEWLINE+NEWLINE+"--"+BOUNDARY+NEWLINE+'Content-Disposition: form-data; name="File"; filename="'+name+'"'+NEWLINE+"Content-Type: "+utils.getContentType(path.extname(name))+NEWLINE+NEWLINE;req.write(header);stream.on("end",function(){req.end(NEWLINE+NEWLINE+"--"+BOUNDARY+"--")});stream.pipe(req,{end:false});return self};exports.trim=function(obj){var type=typeof obj;if(type===STRING)return obj.trim();if(type!==OBJECT)return obj;Object.keys(obj).forEach(function(name){var val=obj[name];if(typeof val===OBJECT){exports.trim(val);return}if(typeof val!==STRING)return;obj[name]=val.trim()});return obj};exports.noop=function(){};exports.httpStatus=function(code,addCode){return(addCode||true?code+": ":"")+http.STATUS_CODES[code]};exports.extend=function(target,source,rewrite){if(target===null||source===null)return target;if(typeof target!==OBJECT||typeof source!==OBJECT)return target;var keys=Object.keys(source);var i=keys.length;while(i--){var key=keys[i];if(rewrite||typeof target[key]===UNDEFINED)target[key]=source[key]}return target};exports.copy=function(target,source,rewrite){if(target===null||source===null)return target;if(typeof target!==OBJECT||typeof source!==OBJECT)return target;if(typeof rewrite===UNDEFINED)rewrite=true;var keys=Object.keys(source);var i=keys.length;while(i--){var key=keys[i];if(typeof target[key]===UNDEFINED)continue;if(rewrite){target[key]=source[key];continue}target[key]=source[key]}return target};exports.reduce=function(source,prop){if(source===null||prop===null)return source;var type=typeof prop;if(prop instanceof Array){Object.keys(source).forEach(function(o){if(prop.indexOf(o)===-1)delete source[o]})}if(type===OBJECT){var obj=Object.keys(prop);Object.keys(source).forEach(function(o){if(obj.indexOf(o)===-1)delete source[o]})}return source};exports.isRelative=function(url){return!(url.substring(0,2)==="//"||url.indexOf("http://")!==-1||url.indexOf("https://")!==-1)};exports.htmlEncode=function(str){var type=typeof str;if(type===UNDEFINED)return"";if(type!==STRING)str=str.toString();return str.htmlEncode()};exports.htmlDecode=function(str){var type=typeof str;if(type===UNDEFINED)return"";if(type!==STRING)str=str.toString();return str.htmlDecode()};exports.isStaticFile=function(url){var pattern=/\.\w{2,8}($|\?)+/g;return pattern.test(url)};exports.isNullOrEmpty=function(str){if(typeof str!==STRING)return true;return str.length===0};exports.parseInt=function(obj,def){var type=typeof obj;if(type===UNDEFINED)return def||0;var str=type!==STRING?obj.toString():obj;return str.parseInt(def,10)};exports.parseFloat=function(obj,def){var type=typeof obj;if(type===UNDEFINED)return def||0;var str=type!==STRING?obj.toString():obj;return str.parseFloat(def)};exports.isArray=function(obj){return util.isArray(obj)};exports.isDate=function(obj){return util.isDate(obj)};exports.getContentType=function(ext){if(ext[0]===".")ext=ext.substring(1);var extension={ai:"application/postscript",appcache:"text/cache-manifest",avi:"video/avi",bin:"application/octet-stream",bmp:"image/bmp",css:"text/css",less:"text/css",sass:"text/css",csv:"text/csv",doc:"application/msword",docx:"application/msword",dtd:"application/xml-dtd",eps:"application/postscript",exe:"application/octet-stream",gif:"image/gif",gzip:"application/x-gzip",htm:"text/html",html:"text/html",ico:"image/x-icon",ics:"text/calendar",ifb:"text/calendar",jpe:"image/jpeg",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript",json:"application/json",m4a:"audio/mp4a-latm",m4v:"video/x-m4v",md:"text/markdown",mid:"audio/midi",midi:"audio/midi",mov:"video/quicktime",mp3:"audio/mpeg",mp4:"video/mp4",mpe:"video/mpeg",mpeg:"video/mpeg",mpg:"video/mpeg",mpga:"audio/mpeg",mv4:"video/mv4",ogg:"application/ogg",pdf:"application/pdf",png:"image/png",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.ms-powerpoint",ps:"application/postscript",rar:"application/x-rar-compressed",rtf:"text/rtf",sh:"application/x-sh",svg:"image/svg+xml",swf:"application/x-shockwave-flash",tar:"application/x-tar",tif:"image/tiff",tiff:"image/tiff",txt:"text/plain",wav:"audio/x-wav",webp:"image/webp",woff:"font/woff",xht:"application/xhtml+xml",xhtml:"application/xhtml+xml",xls:"application/vnd.ms-excel",xlsx:"application/vnd.ms-excel",xml:"application/xml",xpm:"image/x-xpixmap",xsl:"application/xml",xslt:"application/xslt+xml",zip:"application/zip"};return extension[ext.toLowerCase()]||"application/octet-stream"};exports.etag=function(text,version){var sum=0;var length=text.length;for(var i=0;i<length;i++)sum+=text.charCodeAt(i);return sum.toString()+(version?":"+version:"")};exports.path=function(path,delimiter){delimiter=delimiter||"/";if(path[path.length-1]===delimiter)return path;return path+delimiter};exports.random=function(max,min){max=max||1e5;min=min||0;return Math.floor(Math.random()*(max-min+1))+min};exports.GUID=function(max){max=max||40;var rnd=function(){return Math.floor(Math.random()*65536).toString(16)};var str="";for(var i=0;i<max/4+1;i++)str+=rnd();return str.substring(0,max)};exports.validate=function(model,properties,prepare,builder,resource,path){if(typeof builder===FUNCTION&&typeof resource===UNDEFINED){resource=builder;builder=null}var error=builder;var current=typeof path===UNDEFINED?"":path+".";var isSchema=false;var schemaName="";var definition=null;if(!(error instanceof builders.ErrorBuilder))error=new builders.ErrorBuilder(resource);if(typeof properties===STRING){var schema=builders.validation(properties);if(schema.length!==0){schemaName=properties;properties=schema;isSchema=true;definition=builders.schema(schemaName)}else properties=properties.replace(/\s/g,"").split(",")}if(typeof model===UNDEFINED||model===null)model={};if(typeof prepare!==FUNCTION)throw new Error("Validate hasn't any method to validate properties.\nDefine delegate: framework.onValidate ...");for(var i=0;i<properties.length;i++){var name=properties[i].toString();var value=model[name];var type=typeof value;value=(type===FUNCTION?model[name]():model[name])||"";if(type!==OBJECT&&isSchema){if(builders.isJoin(definition[name]))type=OBJECT}if(type===OBJECT){if(isSchema){var schema=builders.schema(schemaName)||null;if(schema!==null){schema=schema[name]||null;if(schema!==null){var isArray=schema[0]==="[";if(isArray)schema=schema.substring(1,schema.length-1);if(isArray){if(!(value instanceof Array)){error.add(name,"@");continue}var sublength=value.length;for(var j=0;j<sublength;j++)exports.validate(value[j],schema,prepare,error,resource,current+name);continue}exports.validate(value,schema,prepare,error,resource,current+name);continue}}}exports.validate(value,properties,prepare,error,resource,current+name);continue}var result=prepare(name,value,current+name);if(typeof result===UNDEFINED)continue;type=typeof result;if(type===STRING){error.add(name,result,current+name);continue}if(type===BOOLEAN){if(!result)error.add(name,"@",current+name);continue}if(result.isValid===false)error.add(name,result.error,current+name)}return error};exports.isValid=function(valid,error){return{isValid:valid,error:error||"@"}};exports.isEmail=function(str){return(str||"").toString().isEmail()};exports.isURL=function(str){return(str||"").toString().isURL()};exports.combine=function(){return"."+path.join.apply(this,arguments)};exports.removeDiacritics=function(str){var dictionaryA=["á","ä","č","ď","é","ě","ť","ž","ú","ů","ü","í","ï","ô","ó","ö","š","ľ","ĺ","ý","ÿ","č","ř"];var dictionaryB=["a","a","c","d","e","e","t","z","u","u","u","i","i","o","o","o","s","l","l","y","y","c","r"];var buf="";var length=str.length;for(var i=0;i<length;i++){var c=str[i];var isUpper=false;var index=dictionaryA.indexOf(c);if(index===-1){index=dictionaryA.indexOf(c.toLowerCase());isUpper=true}if(index===-1){buf+=c;continue}c=dictionaryB[index];if(isUpper)c=c.toUpperCase();buf+=c}return buf};exports.encode_WS=function(data){var bytesFormatted=[];bytesFormatted[0]=129;if(data.length<=125){bytesFormatted[1]=data.length}else if(data.length>=126&&data.length<=65535){bytesFormatted[1]=126;bytesFormatted[2]=data.length>>8&255;bytesFormatted[3]=data.length&255}else{bytesFormatted[1]=127;bytesFormatted[2]=data.length>>56&255;bytesFormatted[3]=data.length>>48&255;bytesFormatted[4]=data.length>>40&255;bytesFormatted[5]=data.length>>32&255;bytesFormatted[6]=data.length>>24&255;bytesFormatted[7]=data.length>>16&255;bytesFormatted[8]=data.length>>8&255;bytesFormatted[9]=data.length&255}var length=data.length;for(var i=0;i<length;i++)bytesFormatted.push(data.charCodeAt(i));return bytesFormatted};exports.decode_WS=function(data){var datalength=data[1]&127;var indexFirstMask=2;if(datalength===126)indexFirstMask=4;else if(datalength===127)indexFirstMask=10;var masks=data.slice(indexFirstMask,indexFirstMask+4);var i=indexFirstMask+4;var index=0;var output="";var length=data.length;while(i<length)output+=String.fromCharCode(data[i++]^masks[index++%4]);return output};exports.distance=function(lat1,lon1,lat2,lon2){var R=6371;var dLat=(lat2-lat1).toRad();var dLon=(lon2-lon1).toRad();var a=Math.sin(dLat/2)*Math.sin(dLat/2)+Math.cos(lat1.toRad())*Math.cos(lat2.toRad())*Math.sin(dLon/2)*Math.sin(dLon/2);var c=2*Math.atan2(Math.sqrt(a),Math.sqrt(1-a));return(R*c).floor(3)};exports.ls=function(path,callback,filter){var filelist=new FileList;filelist.onComplete=callback;filelist.onFilter=filter||null;filelist.walk(path)};Date.prototype.add=function(type,value){var self=this;switch(type){case"s":case"ss":case"second":case"seconds":self.setSeconds(self.getSeconds()+value);return self;case"m":case"mm":case"minute":case"minutes":self.setMinutes(self.getMinutes()+value);return self;case"h":case"hh":case"hour":case"hours":self.setHours(self.getHours()+value);return self;case"d":case"dd":case"day":case"days":self.setDate(self.getDate()+value);return self;case"M":case"MM":case"month":case"months":self.setMonth(self.getMonth()+value);return self;case"y":case"yyyy":case"year":case"years":self.setFullYear(self.getFullYear()+value);return self}return self};Date.prototype.format=function(format){var self=this;var h=self.getHours();var m=self.getMinutes().toString();var s=self.getSeconds().toString();var M=(self.getMonth()+1).toString();var yyyy=self.getFullYear().toString();var d=self.getDate().toString();var a="AM";var H=h.toString();if(h>=12){h-=12;a="PM"}if(h===0)h=12;h=h.toString();var hh=h.padLeft(2,"0");var HH=H.padLeft(2,"0");var mm=m.padLeft(2,"0");var ss=s.padLeft(2,"0");var MM=M.padLeft(2,"0");var dd=d.padLeft(2,"0");var yy=yyyy.substring(2);return format.replace(/yyyy/g,yyyy).replace(/yy/g,yy).replace(/MM/g,MM).replace(/M/g,M).replace(/dd/g,dd).replace(/d/g,d).replace(/HH/g,HH).replace(/H/g,H).replace(/hh/g,hh).replace(/h/g,h).replace(/mm/g,mm).replace(/m/g,m).replace(/ss/g,ss).replace(/s/g,ss).replace(/a/g,a)};if(!String.prototype.trim){String.prototype.trim=function(){return this.replace(/^[\s]+|[\s]+$/g,"")}}String.prototype.count=function(text){var index=0;var count=0;do{index=this.indexOf(text,index+text.length);if(index>0)count++}while(index>0);return count};String.prototype.parseDate=function(){return new Date(this.toString())};String.prototype.contains=function(value,mustAll){var str=this.toString();if(typeof value===STRING)return str.indexOf(value)!==-1;var length=value.length;for(var i=0;i<length;i++){var exists=str.indexOf(value[i])!==-1;if(mustAll){if(!exists)return false}else if(exists)return true}return mustAll?true:false};String.prototype.configuration=function(){var arr=this.split("\n");var length=arr.length;var obj={};for(var i=0;i<length;i++){var str=arr[i];if(str==="")continue;if(str.substring(0,2)==="//")continue;var index=str.indexOf(":");if(index===-1)continue;obj[str.substring(0,index).trim()]=str.substring(index+1).trim()}return obj};String.prototype.format=function(){var formatted=this;var length=arguments.length;for(var i=0;i<length;i++){var regexp=new RegExp("\\{"+i+"\\}","gi");formatted=formatted.replace(regexp,arguments[i])}return formatted};String.prototype.htmlEncode=function(){return this.replace(/\&/g,"&").replace(/\>/g,">").replace(/\</g,"<").replace(/\"/g,""")};String.prototype.htmlDecode=function(){return this.replace(/>/g,">").replace(/\</g,"<").replace(/\"/g,'"').replace(/&/g,"&")};String.prototype.urlEncode=function(){return encodeURIComponent(this)};String.prototype.urlDecode=function(){return decodeURIComponent(this)};String.prototype.params=function(obj){var formatted=this.toString();if(typeof obj===UNDEFINED||obj===null)return formatted;var reg=/\{[^}\n]*\}/g;var match=formatted.match(reg);if(match===null)return formatted;var length=match.length;for(var i=0;i<length;i++){var prop=match[i];var isEncode=false;var name=prop.substring(1,prop.length-1).trim();var format="";var index=name.indexOf("|");if(index!==-1){format=name.substring(index+1,name.length).trim();name=name.substring(0,index).trim()}if(prop.substring(0,2)==="{!")name=name.substring(1);else isEncode=true;var val;if(name.indexOf(".")!==-1){var arr=name.split(".");if(arr.length===2)val=obj[arr[0]][arr[1]];else if(arr.length===3)val=obj[arr[0]][arr[1]][arr[3]];else if(arr.length===4)val=obj[arr[0]][arr[1]][arr[3]][arr[4]];else if(arr.length===5)val=obj[arr[0]][arr[1]][arr[3]][arr[4]][arr[5]]}else val=name.length===0?obj:obj[name];if(typeof val===FUNCTION)val=val(index);if(typeof val===UNDEFINED)return;if(format.length>0){var type=typeof val;if(type===STRING){var max=parseInt(format,10);if(!isNaN(max))val=val.max(max+3,"...")}else if(type===NUMBER||util.isDate(val))val=val.format(format)}val=val.toString().dollar();formatted=formatted.replace(prop,isEncode?exports.htmlEncode(val):val)}return formatted};String.prototype.max=function(length,chars){var str=this.toString();chars=chars||"...";return str.length>length?str.substring(0,length-chars.length)+chars:str};String.prototype.isJSON=function(){var self=this;if(self.length<=1)return false;var a=self[0];var b=self[self.length-1];return a==='"'&&b==='"'||a==="["&&b==="]"||a==="{"&&b==="}"};String.prototype.isURL=function(){var str=this.toString();if(str.length<=7)return false;return regexpUrl.test(str)};String.prototype.isEmail=function(){var str=this.toString();if(str.length<=4)return false;if(str[0]==="."||str[str.length-1]===".")return false;return regexpMail.test(str)};String.prototype.parseInt=function(def){var num=0;var str=this.toString();if(str.substring(0,1)==="0")num=parseInt(str.replace(/\s/g,"").substring(1),10);else num=parseInt(str.replace(/\s/g,""),10);if(isNaN(num))return def||0;return num};String.prototype.parseFloat=function(def){var num=0;var str=this.toString();if(str.substring(0,1)==="0")num=parseFloat(str.replace(/\s/g,"").substring(1).replace(",","."));else num=parseFloat(str.replace(/\s/g,"").replace(",","."));if(isNaN(num))return def||0;return num};String.prototype.toUnicode=function(){var result="";var self=this.toString();var length=self.length;for(var i=0;i<length;++i){if(self.charCodeAt(i)>126||self.charCodeAt(i)<32)result+="\\u"+self.charCodeAt(i).hex(4);else result+=self[i]}return result};String.prototype.fromUnicode=function(){var str=this.replace(/\\u([\d\w]{4})/gi,function(match,v){return String.fromCharCode(parseInt(v,16))});return unescape(str)};String.prototype.sha1=function(){var hash=crypto.createHash("sha1");hash.update(this.toString(),ENCODING);return hash.digest("hex")};String.prototype.md5=function(){var hash=crypto.createHash("md5");hash.update(this.toString(),ENCODING);return hash.digest("hex")};String.prototype.encode=function(key,isUnique){var str="0"+this.toString();var data_count=str.length;var key_count=key.length;var change=str[data_count-1];var random=isUnique||true?exports.random(120)+40:65;var count=data_count+random%key_count;var values=[];var index=0;values[0]=String.fromCharCode(random);var counter=this.length+key.length;for(var i=count-1;i>0;i--){index=str.charCodeAt(i%data_count);values[i]=String.fromCharCode(index^(key.charCodeAt(i%key_count)^random))}var hash=new Buffer(counter+"="+values.join(""),ENCODING).toString("base64").replace(/\//g,"-").replace(/\+/g,"_");index=hash.indexOf("=");if(index>0)return hash.substring(0,index);return hash};String.prototype.decode=function(key){var values=this.toString().replace(/\-/g,"/").replace(/\_/g,"+");var mod=values.length%4;if(mod>0){for(var i=0;i<mod;i++)values+="="}values=new Buffer(values,"base64").toString(ENCODING);var index=values.indexOf("=");if(index===-1)return"";var counter=parseInt(values.substring(0,index),10);if(isNaN(counter))return"";values=values.substring(index+1);var count=values.length;var random=values.charCodeAt(0);var key_count=key.length;var data_count=count-random%key_count;var decrypt_data=[];for(var i=data_count-1;i>0;i--){index=values.charCodeAt(i)^(random^key.charCodeAt(i%key_count));decrypt_data[i]=String.fromCharCode(index)}var val=decrypt_data.join("");if(counter!==val.length+key.length)return"";return val};String.prototype.base64ToFile=function(filename,callback){var self=this.toString();var index=self.indexOf(",");if(index===-1)index=0;else index++;if(callback)fs.writeFile(filename,self.substring(index),"base64",callback);else fs.writeFile(filename,self.substring(index),"base64",exports.noop);return this};String.prototype.base64ContentType=function(){var self=this.toString();var index=self.indexOf(";");if(index===-1)return"";return self.substring(5,index)};String.prototype.removeDiacritics=function(){return exports.removeDiacritics(this)};String.prototype.indent=function(max,c){var self=this.toString();return new Array(max+1).join(c||" ")+self};String.prototype.isNumber=function(isDecimal){var self=this.toString();var length=self.length;if(length===0)return false;isDecimal=isDecimal||false;for(var i=0;i<length;i++){var ascii=self.charCodeAt(i);if(isDecimal){if(ascii===44||ascii===46){isDecimal=false;continue}}if(ascii<48||ascii>57)return false}return true};String.prototype.padLeft=function(max,c){var self=this.toString();return new Array(Math.max(0,max-self.length+1)).join(c||" ")+self};String.prototype.padRight=function(max,c){var self=this.toString();return self+new Array(Math.max(0,max-self.length+1)).join(c||" ")};String.prototype.insert=function(index,value){var str=this.toString();var a=str.substring(0,index);var b=value.toString()+str.substring(index);return a+b};String.prototype.dollar=function(){var str=this.toString();var index=str.indexOf("$",0);while(index!==-1){if(str[index+1]==="$")str=str.insert(index,"$");index=str.indexOf("$",index+2)}return str.toString()};String.prototype.link=function(max){max=max||60;var self=this.toString().trim().toLowerCase().removeDiacritics();var builder="";var length=self.length;for(var i=0;i<length;i++){var c=self[i];var code=self.charCodeAt(i);if(builder.length>=max)break;if(code>31&&code<48){if(builder[builder.length-1]==="-")continue;builder+="-";continue}if(code>47&&code<58){builder+=c;continue}if(code>94&&code<123){builder+=c;continue}}return builder};String.prototype.pluralize=function(zero,one,few,other){var str=this.toString();return str.parseInt().pluralize(zero,one,few,other)};String.prototype.isBoolean=function(){var self=this.toString().toLowerCase();return self==="true"||self==="false"?true:false};Number.prototype.floor=function(decimals){return Math.floor(this*Math.pow(10,decimals))/Math.pow(10,decimals)};Number.prototype.padLeft=function(max,c){return this.toString().padLeft(max,c||"0")};Number.prototype.padRight=function(max,c){return this.toString().padRight(max,c||"0")};Number.prototype.format=function(format){var index=0;var num=this.toString();var beg=0;var end=0;var max=0;var output="";if(typeof format===STRING){var d=false;for(var i=0;i<format.length;i++){var c=format[i];if(c==="#"){if(d)end++;else beg++}if(c===".")d=true}var strBeg=num;var strEnd="";index=num.indexOf(".");if(index!==-1){strBeg=num.substring(0,index);strEnd=num.substring(index+1)}if(strBeg.length>beg){max=strBeg.length-beg;var tmp="";for(var i=0;i<max;i++)tmp+="#";format=tmp+format}if(strBeg.length<beg)strBeg=strBeg.padLeft(beg," ");if(strEnd.length<end)strEnd=strEnd.padRight(end,"0");if(strEnd.length>end)strEnd=strEnd.substring(0,end);d=false;index=0;var skip=true;var length=format.length;for(var i=0;i<length;i++){var c=format[i];if(c!=="#"){if(skip)continue;if(c==="."){d=true;index=0}output+=c;continue}var value=d?strEnd[index]:strBeg[index];if(skip)skip=[","," "].indexOf(value)!==-1;if(!skip)output+=value;index++}return output}output="### ### ###";beg=num.indexOf(".");max=format||0;if(max===0&&num!=-1)max=num.length-(beg+1);if(max>0){output+=".";for(var i=0;i<max;i++)output+="#"}return this.format(output)};Number.prototype.pluralize=function(zero,one,few,other){var num=this;var value="";if(num===0)value=zero||"";else if(num===1)value=one||"";else if(num>1&&num<5)value=few||"";else value=other;var beg=value.indexOf("#");var end=value.lastIndexOf("#");if(beg===-1)return value;var format=value.substring(beg,end+1);return num.format(format)+value.replace(format,"")};Number.prototype.hex=function(length){var str=this.toString(16).toUpperCase();while(str.length<length)str="0"+str;return str};Number.prototype.condition=function(ifTrue,ifFalse){return(this%2===0?ifTrue:ifFalse)||""};Number.prototype.VAT=function(percentage,decimals,includedVAT){var num=this;var type=typeof decimals;if(type===BOOLEAN){var tmp=includedVAT;includedVAT=decimals;decimals=tmp;type=typeof decimals}if(type===UNDEFINED)decimals=2;if(typeof includedVAT===UNDEFINED)includedVAT=true;if(percentage===0||num===0)return num;return includedVAT?(num/(percentage/100+1)).floor(decimals):(num*(percentage/100+1)).floor(decimals)};Number.prototype.discount=function(percentage,decimals){var num=this;var type=typeof decimals;if(type===UNDEFINED)decimals=2;return(num-num/100*percentage).floor(decimals)};Number.prototype.parseDate=function(plus){return new Date(this+(plus||0))};if(typeof Number.prototype.toRad==="undefined"){Number.prototype.toRad=function(){return this*Math.PI/180}}Boolean.prototype.condition=function(ifTrue,ifFalse){return(this?ifTrue:ifFalse)||""};Array.prototype.take=function(count){var arr=[];var self=this;var length=self.length;for(var i=0;i<length;i++){arr.push(self[i]);if(arr.length>=count)return arr}return arr};Array.prototype.skip=function(count){var arr=[];var self=this;var length=self.length;for(var i=0;i<length;i++){if(i>=count)arr.push(self[i])}return arr};Array.prototype.where=function(cb){var self=this;var selected=[];var length=self.length;for(var i=0;i<length;i++){if(cb.call(self,self[i],i))selected.push(self[i])}return selected};Array.prototype.find=function(cb){var self=this;var length=self.length;for(var i=0;i<length;i++){if(cb.call(self,self[i],i))return self[i]}return null};Array.prototype.remove=function(cb){var self=this;var arr=[];var length=self.length;for(var i=0;i<length;i++){if(!cb.call(self,self[i],i))arr.push(self[i])}return arr};Array.prototype.random=function(){var self=this;return self[exports.random(self.length-1)]};Array.prototype.waiting=function(onItem,callback){var self=this;var item=self.shift();if(typeof item===UNDEFINED){if(callback)callback();return}onItem.call(self,item,function(){self.waiting(onItem,callback)});return self};Array.prototype.randomize=function(){var self=this;var random=(Math.floor(Math.random()*1e8)*10).toString();var index=0;var old=0;self.sort(function(a,b){var c=random[index++];if(typeof c===UNDEFINED){c=random[0];index=0}if(old>c){old=c;return-1}if(old===c){old=c;return 0}old=c;return 1});return self};function AsyncTask(owner,name,fn,cb,waiting){this.handlers={oncomplete:this.complete.bind(this)};this.isRunning=0;this.owner=owner;this.name=name;this.fn=fn;this.cb=cb;this.waiting=waiting;this.interval=null;this.isCanceled=false}AsyncTask.prototype.run=function(){var self=this;try{self.isRunning=1;self.owner.tasksWaiting[self.name]=true;self.owner.emit("begin",self.name);var timeout=self.owner.tasksTimeout[self.name];if(timeout>0)self.interval=setTimeout(self.timeout.bind(self),timeout);self.fn(self.handlers.oncomplete)}catch(ex){self.owner.emit("error",self.name,ex);self.complete()}return self};AsyncTask.prototype.timeout=function(timeout){var self=this;if(timeout>0){clearTimeout(self.interval);setTimeout(self.timeout.bind(self),timeout);return self}if(timeout<=0){clearTimeout(self.interval);setTimeout(self.timeout.bind(self),timeout);return self}self.cancel(true);return self};AsyncTask.prototype.cancel=function(isTimeout){var self=this;self.isCanceled=true;if(isTimeout)self.owner.emit("timeout",self.name);else self.owner.emit("cancel",self.name);self.fn=null;self.cb=null};AsyncTask.prototype.complete=function(){var item=this;var self=item.owner;item.isRunning=2;delete self.tasksPending[item.name];delete self.tasksWaiting[item.name];if(!item.isCanceled){try{self.emit("end",item.name);if(item.cb)item.cb()}catch(ex){self.emit("error",ex,item.name)}}self.reload();self.refresh();return self};function Async(owner){this._max=0;this._count=0;this._isRunning=false;this.owner=owner;this.onComplete=[];this.tasksPending={};this.tasksWaiting={};this.tasksAll=[];this.tasksTimeout={}}Async.prototype={get count(){return this._count},get percentage(){var self=this;return 100-Math.floor(self._count*100/self._max)}};Async.prototype.__proto__=new events.EventEmitter;Async.prototype.reload=function(){var self=this;self.tasksAll=Object.keys(self.tasksPending);self.emit("percentage",self.percentage);return self};Async.prototype.cancel=function(name){var self=this;if(typeof name===UNDEFINED){for(var i=0;i<self._count;i++)self.cancel(tasksAll[i]);return true}var task=self.tasksPending[name];if(!task)return false;delete self.tasksPending[name];delete self.tasksWaiting[name];task.cancel();self.reload();self.refresh();return true};Async.prototype.await=function(name,fn,cb){var self=this;if(typeof name===FUNCTION){cb=fn;fn=name;name=exports.GUID(6)}if(typeof self.tasksPending[name]!==UNDEFINED)return false;self.tasksPending[name]=new AsyncTask(self,name,fn,cb,null);self._max++;self.reload();self.refresh();return true};Async.prototype.wait=function(name,waitingFor,fn,cb){var self=this;if(typeof waitingFor===FUNCTION){cb=fn;fn=waitingFor;waitingFor=name;name=exports.GUID(6)}if(typeof self.tasksPending[name]!==UNDEFINED)return false;self.tasksPending[name]=new AsyncTask(self,name,fn,cb,waitingFor);self._max++;self.reload();self.refresh();return true};Async.prototype.complete=function(fn){return this.run(fn)};Async.prototype.run=function(fn){var self=this;self._isRunning=true;if(fn)self.onComplete.push(fn);self.refresh();return self};Async.prototype.isRunning=function(name){var self=this;if(!name)return self._isRunning;var task=self.tasksPending[name];if(!task)return false;return task.isRunning===1};Async.prototype.isWaiting=function(name){var self=this;var task=self.tasksPending[name];if(!task)return false;return task.isRunning===0};Async.prototype.isPending=function(name){var self=this;var task=self.tasksPending[name];if(!task)return false;return true};Async.prototype.timeout=function(name,timeout){var self=this;if(timeout<=0||typeof timeout===UNDEFINED){delete self.tasksTimeout[name];return self}self.tasksTimeout[name]=timeout;return self};Async.prototype.refresh=function(name){var self=this;if(!self._isRunning)return self;self._count=self.tasksAll.length;for(var i=0;i<self._count;i++){var task=self.tasksPending[self.tasksAll[i]];
manufacturer.models.map(model => { if (vehicle.makeModelVersion.startsWith(model.n, manufacturer.name.length + 1)) { vehicle.model = model.n; vehicle.version = vehicle.makeModelVersion .replace(vehicle.manufacturer + ' ' + vehicle.model, '') .replace(/^\s+/, '') .replace(/\s+$/, ''); } }) } }); return vehicle; } source = source.map(mapVehiclesToModels); fs.writeFile(__dirname + '/../data/data.json', JSON.stringify(source), 'utf8', (err) => { if (err) return console.log(err); console.log("The data.json file was created!"); }); // build module for test data var testData = page3; testData = testData.map(mapVehiclesToModels); fs.writeFile(__dirname + '/../data/testData.js', 'module.exports = ' + JSON.stringify(testData, null, ' '), 'utf8', (err) => { if (err) return console.log(err); console.log("The testData.js file was created!"); });
steamClient.on('servers', function (servers) { fs.writeFile('servers', JSON.stringify(servers)); });
event.on('write_file',function(){ fs.writeFile(__dirname+'/dbcopy.js', str, function (err) { if (err) throw err; console.log('It\'s saved!'); }); });
function writeFile(object) { fs.writeFile(dir+'/'+object+".json", JSON.stringify(data[object]), function(err){ console.log(err);}); }
if("function"===typeof require){var fs=require("fs"),path=require("path"),sys=require("sys"),exec=require("child_process").exec,out_;readStringFromFile=function(a){return fs.readFileSync(path.resolve(RunningFileDirectory,a),"utf8")};writeStringToFile=function(a,b){fs.writeFile(path.resolve(__dirname,a),b);return"undefined"};getCurrentDirectory=function(){return __dirname}}
'package.json:write': ['package.json:read', function(callback, results) { var options = JSON.parse(results['package.json:read'].toString()); options = merge(true, options, customOptions); fs.writeFile(PACKAGE_JSON, JSON.stringify(options), callback); }],
function (stdout, stderr, cb) { var pkgPath = tempPath + '/lola/package.json'; var pkg = require(pkgPath); pkg.dependencies['lola-plugin-pola'] = ''; fs.writeFile(pkgPath, JSON.stringify(pkg), cb); },
setTimeout(function () { fs.writeFile('configs/fileInfo.json', JSON.stringify(self.fileInfo), function (err) { if (err) console.log(err) }) }, 1)
promises.push(new Promise((res, rej) => { fs.writeFile(`./.dist/${handler.name}.js`, content, 'utf8', (err) => { if(err) res(err) else rej() }) }))
//Pass in path to saved gene pool function conductEvolutionGeneration(pool){ //var pool = wrangler.createPool("temp",5); console.log("New Generation Begins================================================"); var results = wrangler.tournament(pool); //calculate fitnesses var totalFitness = 0; for(var i in results){ var cur = results[i]; // use wins as a fitness function (wins * ratio wasn't working great) cur.fitness = cur.wins; totalFitness += cur.fitness; } //Normalize fitnesses: // (resulting fitness should be % chance of reproducing) for(var i in results){ var cur = results[i]; cur.fitness = cur.fitness / totalFitness; } //Create new generation var newGeneration = []; //Top 3 survive results.sort((a,b) => (b.fitness - a.fitness)); for(var i = 0; i < 3; i++){ results[i].ai.generationsSurvived += 1; newGeneration.push(results[i].ai); } //Reproduce (create 23 new AIs) for(var i = 0; i < 23; i++){ //Choose a random parent A var rand = Math.random(); var runningTotal = 0; var parentA = null; var parentB = null; for(var j = 0; j < results.length; j++){ runningTotal += results[j].fitness; if (runningTotal > rand){ //Choose this person as parent A parentA = results[j].ai; break; } }//find parentA //Just in case: if(parentA == null){ parentA = results[results.length - 1].ai; } //Chooe parent B, avoiding self-incest if possible var counter = 0; while(true){ rand = Math.random(); runningTotal = 0; for(var j = 0; j < results.length; j++){ runningTotal += results[j].fitness; if(runningTotal > rand){ parentB = results[j].ai; break; } } //Just in case: if(parentB == null){ parentB = results[results.length - 1].ai; } counter += 1; if(parentA != parentB || counter > 20){ break; } }//find parentB newGeneration.push(wrangler.reproduce(parentA,parentB)); } //4 randoms are introduced for(var i = 0; i < 4; i++){ var newAI = new ANN(); newAI.postConstructor(); newGeneration.push(newAI); } //Record some stats about prev. generation and new generation: var data = "Previous generation fitnesses:\n"; for (var i in results){ data += results[i].ai.fullName() + " (" + results[i].ai.generationsSurvived + "):\nFitness " + results[i].fitness + ", " + results[i].wins + " wins, for/against ratio: " + results[i].ratio + "\n"; } data += "\nNew generation names:\n"; for (var i in newGeneration){ data += newGeneration[i].fullName() + "\n"; } //This should recurr infinitely, but the files get written intermittently // so stopping execution manually doesn't result in data loss. fs.writeFile("Evolutioninformation.txt",data,function(){ wrangler.poolToFile(newGeneration,"mainGenePool.json",function(){ conductEvolutionGeneration(newGeneration) }); }); }//conductEvolution
} output += '</table></div>'; return output; } try { fs.accessSync('config/Shop.json', fs.F_OK); let raw = JSON.parse(fs.readFileSync('config/Shop.json', 'utf8')); Shop = raw; } catch (e) { fs.writeFile('config/Shop.json', "{}", function (err) { if (err) { console.error('Error while loading Shop: ' + err); Shop = { closed: true, }; writeJSON = false; } else { console.log("config/Shop.json not found, creating a new one..."); } }); } /* * Shop end */ /* * Dice start */
var writeOutput = function() { fs.writeFile(outputFile, JSON.stringify(buffer), function() { console.log('Converted to ' + outputFile); }); };
function changeParsed(err, log){ if (err) { return done(err); } fs.writeFile('CHANGELOG.md', log, done); }