Example #1
0
Reporting.prototype.logErrorTXT = function (error) {
    fs.appendFile(constantes.PATH_FILE_ERROR_REPORTING, error + "\n", function(err) {
	if(err)console.log(err);
    });
};
Example #2
0
  var filesStr = filesToInclude.join(' ');
  var isBasicBuild = modulesToInclude.length === 0;

  var minFilesStr = filesToInclude
    .filter(function(f) { return f !== '' })
    .map(function(fileName) {
      return 'tmp/' + fileName.replace(/\//g, '^');
    })
    .join(' ');

  var fileName = isBasicBuild ? 'fabric' : modulesToInclude.join(',');

  var escapedHeader = distFileContents.replace(/`/g, '\\`');
  var path = '../fabricjs.com/build/files/' + fileName + '.js';
  fs.appendFile('build.sh',
    'echo "' + escapedHeader + '" > ' + path + ' && cat ' +
    filesStr + ' >> ' + path + '\n');

  path = '../fabricjs.com/build/files/' + fileName + '.min.js';
  fs.appendFile('build.sh',
    'echo "' + escapedHeader + '" > ' + path + ' && cat ' +
    minFilesStr + ' >> ' + path + '\n')
}
else {
  // Change the current working directory
  process.chdir(distributionPath);

  appendFileContents(filesToInclude, function() {
    fs.writeFile('all.js', distFileContents, function (err) {
      if (err) {
        console.log(err);
Example #3
0
		  $("#cnnContainer .cnn_maincntnr .cnn_contentarea .cnn_storyarea .cnn_strycntntlft p").each(function(element) {
			//console.log(myfile);
			var paragraph = $(this);
			var text = "\n"+paragraph.text()+"\n";
			fs.appendFile("Articles/CNN/CNN_"+myfile, text, function (err) {});
		  });
Example #4
0
var helper = require("./helper.js");
var util = require("util");
var fs = require('fs');

var sql = "";
for (var i = 1001; i <= 10000; i++) {
	var password = helper.encryptPassword("12345", 20);
	sql += util.format("INSERT INTO `securityInfo` (`id`, `registerEmail`, `salt`, `password`) VALUES ('%s', '*****@*****.**', '%s', '%s');\n",
		i, i, password.salt, password.password);
}
fs.appendFile("securityInfo.sql", sql, function (err) {
	if (err) console.log(err);
});
Example #5
0
var logResult = function (word) {
    word = word || '';
    var str = "执行日期:" + Date().toString() + "\n" + word + "\n";
    fs.appendFile('../notify_url_access.log', str);
};
Example #6
0
var fs = require('fs');
var path= "C:\\Test\\File.txt";
var data= " y estoy orgulloso de ser de el!";

fs.appendFile(path, data, function(error) {
  if (error) {
    console.error("Write error: " + error.message);
  }else {
    console.log("Successfully wrote " + path);
  }
});
Example #7
0
 array.map(function (item) {
     fs.appendFile('./haodf.txt',
         item.departmentName+': '+item.questionsNumber+'\n', function (err) {
             //console.log('The "data to append" was appended to file! ',result); //数据被添加到文件的尾部
         });
 })
function backupRow(row, callback) {
  fs.appendFile('rows_backup.txt', JSON.stringify(row)+'\n', callback);
}
Example #9
0
window.addEventListener('error', function (err) {
	var message = '---error---\n' + err.filename + ':' + err.lineno + '\n' + err.message + '\n\n';
	fs.appendFile(errorLog, message);
	alert(message);
}, false);
Example #10
0
exports.log = function (message) {
    message = '[' + new Date() + '] [Fetcher] ' + message;
    console.log(message);
    fs.appendFile('petitional.log', message + '\n', function(err){ if(err) throw err; });
};
Example #11
0
function startGame() {
  	console.log("Game is starting!");
  	var prolificIds = timeStamp() + "\n";
  	for (i = 0; i < sockets.length; i++) {
  		prolificIds = prolificIds + players[sockets[i]].num + " " + players[sockets[i]].prolificId + "\n";
  	}
  	fs.appendFile('log.txt', prolificIds, function(err) {
  		if (err) throw err;
  	});
  	if (sockets.length % 2 != 0) {
    	console.log(sockets.length);
    	console.log("Shutting down. Can't play with an odd number of players!!!");
    	process.exit();
  	}
  	sockets = shuffleArray(sockets, 0, sockets.length - 1);
  	for (i = 0; i < sockets.length; i++) {
    	var groupNum = 1;
    	if (i >= sockets.length / 2 && sockets.length > 2) {
      		groupNum = 2;
    	}
    	if (i % 2 === 0) {
      		stream.write("drawer: " + players[sockets[i]].num + "   guesser: " + players[sockets[i+1]].num + "\n");
      		console.log("drawer" + "  " + sockets[i].id);
      		players[sockets[i]].type = "drawer";
      		players[sockets[i]].partner = sockets[i+1];
      		players[sockets[i]].group = groupNum;
      		players[sockets[i]].playing = true;
    	} else {
      		console.log("guesser" + "  " + sockets[i].id);
      		players[sockets[i]].type = "guesser";
      		players[sockets[i]].partner = sockets[i-1];
      		players[sockets[i]].group = groupNum;
      		players[sockets[i]].playing = true;

    	}
  	}
  	var word;
  	var wordTwo;
  	if (partOne) {
    	word = words[0][0];
    	wordTwo = wordsTwo[0][0];
  	} else {
    	console.log("We are on round " + round);
    	word = words[round][0];
    	wordTwo = wordsTwo[round][0];
  	}
  	console.log(word + "  " + wordTwo);
  	io.sockets.emit('setroles', players, word, wordTwo, true);
  	if (partOne) {
    	stream.write("\n" + timeStamp() + " Round 1 Starting\nGroup 1 word = " + words[0] + "\nGroup 2 word = " + wordsTwo[0] + "\n");
  	}
  	playing = true;
  	var time = setInterval(swapPartners, 65000);
  	var countdown = 59;
  	var interval = setInterval(function() {
    	io.sockets.emit('starttimer', countdown, words[0][0], wordsTwo[0][0], players);
    	if (countdown === -1) {
        	clearInterval(interval);
        	clearInterval(results);
        	countdown = 59;
    	}
    	countdown = countdown - 1;
  	}, 1000);
  	var results = new setInterval(function() {
    	io.sockets.emit('giveposition');
  	}, 150);

  	function swapPartners() {
    	playing = false;
    	io.sockets.emit('clearcanvas');
    	console.log("Swapping players ");
    	for (i = 0; i < sockets.length; i++) {
      		players[sockets[i]].playing = true;
      		if (players[sockets[i]].type === "guesser") {
        		players[sockets[i]].type = "drawer";
      		} else {
        		players[sockets[i]].type = "guesser";
      		}
    	}	
    	round = round + 1;
    	word = words[round][0];
    	wordTwo = wordsTwo[round][0];
    	console.log(word + "  " + wordTwo)
    	io.sockets.emit('setroles', players, word, wordTwo, false);
    	// CHANGE THIS CODE AFTER DONE TESTING
    	if (round === 37) {
      		clearInterval(time);
      		io.sockets.emit('endgame');
      		//return;
      		setTimeout(endGame, 5000)
    	}
    	// CHANGE THIS CODE AFTER DONE TESTING
    	var newRound = round + 1;
    	stream.write("\n" + timeStamp() + " Round " + newRound + " Starting\nGroup 1 word = " + words[round] + "\nGroup 2 word = " + wordsTwo[round] + "\n");
    	playing = true;
    	var countdown = 59
    	var interval = setInterval(function() {
      		io.sockets.emit('starttimer', countdown, words[round][0], wordsTwo[round][0], players);
      		if (countdown === -1) {
        		clearInterval(results);
        		clearInterval(interval);
        		countdown = 59;
      		}
      		countdown = countdown - 1;
    	}, 1000);
   		var results = new setInterval(function() {
      		io.sockets.emit('giveposition');
    	}, 150);
    	//io.sockets.emit('starttimer');

    	// CHANGED CODE!!!!!!
    	if (round === 20) {
      		partOne = false;
      		io.sockets.emit('parttwo');
      		clearInterval(time);
      		clearInterval(results);
      		clearInterval(interval);
      		setTimeout(changePartners, 35000);
      		return;
    	}
  	}
}
Example #12
0
 save: function (name, score, time, next) {
   var line = name + ',' + score + ',' + time + '\n';
   fs.appendFile(leaderboard, line, next);
 },
Example #13
0
http.createServer(function(request, response) {
    console.log(request.method + " " + request.url);
    if (mocks[request.url]) {
        var mock = mocks[request.url];
        console.log("Found mock file!");
        var filePath = path.join(__dirname, mock);

        var readStream = fileSystem.createReadStream(filePath);
        // read the file into a buffer
        var fileChunks = [];
        var chunksLength = 0;
        readStream.on('data', function (chunk) {
            fileChunks.push(chunk);
            chunksLength += chunk.length;
        });
        readStream.on('end', function() {
            var responseData = Buffer.concat(fileChunks, chunksLength);
            var fileString = responseData.toString();

           // parse the headers.
           // Find header division: (either \n\r\n\r, \n\n, or \r\n\r\n)
            var headerEnd = findPositiveMinimum(fileString.indexOf("\n\n"), fileString.indexOf("\r\n\r\n"), fileString.indexOf("\n\r\n\r"));
            var bodyStart = headerEnd + 2;
            var allHeaders = fileString.substring(0, headerEnd);
            var headersArray = allHeaders.split('\n');
            var headerObj = {};
            var responseCode = 0;
            var isFirst = true;
            headersArray.forEach(function(header)  {
                // Get the response code from first line
                if (isFirst) {
                    var firstLine = header.split(" ");
                    responseCode = firstLine[1];
                    isFirst = false;
                    return; // continue
                }

                var tokens = header.split(": ");
                headerObj[tokens[0]] = tokens[1];
            });

            // write the headers
            response.writeHead(responseCode, headerObj);

            // write the body
            // get the position of the body start in the byte buffer
            var beforeBody = fileString.substring(0,bodyStart);
            var bodyStartIndexInBuffer = Buffer.byteLength(beforeBody);
            response.write(responseData.slice(bodyStartIndexInBuffer));
            response.end();
        });

        // Also mark the mock file as verified
        fileSystem.appendFile(VERIFIED_FILE, mock + "\n", function (err) {
            if (err) throw err;
        });

    }
    else {
        // Forward the api call to DCR
        console.log(api + request.url);
        var options = URL.parse(api + request.url);
        options['method'] = request.method;

        //keep all the headers from the original request
        options['headers'] =  request.headers;

        //set proper host, otherwise we are sending the host of the mock server
        options['headers']['host']=options['host'];

        //clear accept-encoding, if set to compress will come back unreadable
        //there is probably a better solution for this
        options['headers']['accept-encoding']='';

        var forwardReq = http.request(options, function(apiResponseStream) {

            var parts = [];
            var partLength = 0;
            apiResponseStream.on('data',function(buffer){
                parts.push(buffer);
                partLength += buffer.length;
            });

            apiResponseStream.on('end',function(){
                var apiResponsePayload = Buffer.concat(parts, partLength);
                response.writeHead(apiResponseStream.statusCode, apiResponseStream.headers);
                response.write(apiResponsePayload);
                response.end();


                // Also generate a mockfile
                fileSystem.mkdir('generated', undefined, function(err) {
                    if (err) {
                        if (err.code != 'EEXIST')
                            console.log(err);
                    }
                    // successfully created folder
                    var mockfile = fileSystem.createWriteStream("generated"+processUrl(request.url));
                    var headers = "HTTP/1.1 "+ apiResponseStream.statusCode + " " + getStatusText(apiResponseStream.statusCode) + "\n";
                    for (var key in apiResponseStream.headers) {
                        if (key != 'content-length') {
                            var obj = apiResponseStream.headers[key] + "\n";
                            headers += key + ": " + obj;
                        }
                    }
                    headers = headers + "X-Name: " + processUrl(request.url) +"\n";
                    headers = headers + "X-Path: " + request.url +"\n\n";

                    mockfile.write(headers);
                    mockfile.write(apiResponsePayload);
                    console.log("Generated mockfile");
                });
            });

        });
        forwardReq.on('error', function(e) {
            console.log("Error: can't forward request: " + e.message);
        });
        request.pipe(forwardReq);
    }
})
Example #14
0
Users.socketConnect = function (worker, workerid, socketid, ip) {
	let id = '' + workerid + '-' + socketid;
	let connection = new Connection(id, worker, socketid, null, ip);
	connections.set(id, connection);

	if (Monitor.countConnection(ip)) {
		connection.destroy();
		Punishments.bannedIps[ip] = '#cflood';
		return;
	}
	let checkResult = Punishments.checkBanned(ip);
	if (!checkResult && Punishments.checkRangeBanned(ip)) {
		checkResult = '#ipban';
	}
	if (checkResult) {
		if (!Config.quietconsole) console.log('CONNECT BLOCKED - IP BANNED: ' + ip + ' (' + checkResult + ')');
		if (checkResult === '#ipban') {
			connection.send("|popup||modal|Your IP (" + ip + ") is not allowed to connect to PS, because it has been used to spam, hack, or otherwise attack our server.||Make sure you are not using any proxies to connect to PS.");
		} else if (checkResult === '#cflood') {
			connection.send("|popup||modal|PS is under heavy load and cannot accommodate your connection right now.");
		} else {
			connection.send("|popup||modal|Your IP (" + ip + ") was banned while using the username '" + checkResult + "'. Your ban will expire in a few days.||" + (Config.appealurl ? " Or you can appeal at:\n" + Config.appealurl : ""));
		}
		return connection.destroy();
	}
	// Emergency mode connections logging
	if (Config.emergency) {
		fs.appendFile('logs/cons.emergency.log', '[' + ip + ']\n', err => {
			if (err) {
				console.log('!! Error in emergency conns log !!');
				throw err;
			}
		});
	}

	let user = new User(connection);
	connection.user = user;
	// Generate 1024-bit challenge string.
	require('crypto').randomBytes(128, (ex, buffer) => {
		if (ex) {
			// It's not clear what sort of condition could cause this.
			// For now, we'll basically assume it can't happen.
			console.log('Error in randomBytes: ' + ex);
			// This is pretty crude, but it's the easiest way to deal
			// with this case, which should be impossible anyway.
			user.disconnectAll();
		} else if (connection.user) {	// if user is still connected
			connection.challenge = buffer.toString('hex');
			// console.log('JOIN: ' + connection.user.name + ' [' + connection.challenge.substr(0, 15) + '] [' + socket.id + ']');
			let keyid = Config.loginserverpublickeyid || 0;
			connection.sendTo(null, '|challstr|' + keyid + '|' + connection.challenge);
		}
	});

	Dnsbl.reverse(ip, (err, hosts) => {
		if (hosts && hosts[0]) {
			user.latestHost = hosts[0];
			if (Config.hostfilter) Config.hostfilter(hosts[0], user, connection);
			if (user.named && !user.locked && user.group === Config.groupsranking[0]) {
				let shortHost = Users.shortenHost(hosts[0]);
				if (Punishments.lockedRanges[shortHost]) {
					user.send("|popup|You are locked because someone on your ISP has spammed, and your ISP does not give us any way to tell you apart from them.");
					Punishments.rangeLockedUsers[shortHost][user.userid] = 1;
					user.locked = '#range';
					user.updateIdentity();
				}
			}
		} else {
			if (Config.hostfilter) Config.hostfilter('', user, connection);
		}
	});

	Dnsbl.query(connection.ip, isBlocked => {
		if (isBlocked) {
			if (connection.user && !connection.user.locked && !connection.user.autoconfirmed) {
				connection.user.semilocked = '#dnsbl';
			}
		}
	});

	user.joinRoom('global', connection);
};
Example #15
0
"use strict";var fs=require("fs");var path=require("path");var util=require("util");var events=require("events");var VERSION="v2.0.6";var STATUS_UNKNOWN=0;var STATUS_READING=1;var STATUS_WRITING=2;var STATUS_LOCKING=3;var STATUS_PENDING=4;var EXTENSION=".nosql";var EXTENSION_VIEW=".nosql";var EXTENSION_BINARY=".nosql-binary";var EXTENSION_TMP=".nosql-tmp";var EXTENSION_CHANGES=".changelog";var EXTENSION_STORED=".nosql-stored";var EXTENSION_META=".meta";var MAX_WRITESTREAM=2;var MAX_READSTREAM=4;var MAX_BUFFER_SIZE=1024*40;var BINARY_HEADER_LENGTH=2e3;var NEWLINE="\n";var STRING="string";var FUNCTION="function";var UNDEFINED="undefined";var BOOLEAN="boolean";if(typeof setImmediate===UNDEFINED){global.setImmediate=function(cb){process.nextTick(cb)}}function Database(filename,directory,changes){if(typeof directory===BOOLEAN){changes=directory;directory=null}this.isReady=false;this.status_prev=STATUS_UNKNOWN;this.status=STATUS_UNKNOWN;this.changes=typeof changes===UNDEFINED?true:changes===true;this.countRead=0;this.countWrite=0;this.pendingRead=[];this.pendingEach=[];this.pendingLock=[];this.pendingDrop=[];this.pendingWrite=[];this.pendingClear=[];this.isPending=false;if(filename.indexOf(EXTENSION)!==-1)filename=filename.replace(EXTENSION,"");this.filename=filename+EXTENSION;this.filenameTemp=filename+EXTENSION_TMP;this.filenameChanges=filename+EXTENSION_CHANGES;this.filenameStored=filename+EXTENSION_STORED;this.filenameMeta=filename+EXTENSION_META;this.name=path.basename(filename);this.directory=path.dirname(filename);this.views=new Views(this);this.meta={version:VERSION,views:{},stored:{},description:"",created:new Date,custom:null};this.binary=(directory||"").length===0?null:new Binary(this,directory);this.changelog=new Changelog(this,this.filenameChanges);this.file=new FileReader(this);this.stored=new Stored(this,this.filenameStored);this._metaLoad()}function Views(db){this.views={};this.db=db;this.directory=db.directory;this.emit=db.emit}function View(db,name,filename){this.db=db;this.status=STATUS_UNKNOWN;this.countRead=0;this.pendingRead=[];this.pendingOperation=[];this.filename=filename;this.name=name;this.emit=db.emit;this.file=new FileReader(db)}function Stored(db,filename){this.filename=filename;this.db=db;this.stored={};this.cache={};this.isReaded=false}function Binary(db,directory){this.db=db;this.directory=directory;if(directory.length===0)return;if(fs.existsSync(directory))return;fs.mkdirSync(directory)}function Changelog(db,filename){this.filename=filename;this.db=db}function FileReader(db){this.db=db}Database.prototype={get created(){var dt=this.meta.created;if(util.isDate(dt))return dt;if(dt===null||typeof dt===UNDEFINED)return null;return new Date(Date.parse(dt.toString()))}};Database.prototype.__proto__=new events.EventEmitter;Database.prototype.insert=function(arr,fnCallback,changes){var self=this;if(typeof fnCallback===STRING){changes=fnCallback;fnCallback=null}if(!(arr instanceof Array))arr=[arr];var length=arr.length;if(self.status===STATUS_LOCKING||self.status===STATUS_PENDING||self.countWrite>=MAX_WRITESTREAM){for(var i=0;i<length;i++)self.pendingWrite.push({json:arr[i],changes:changes});if(fnCallback)fnCallback(-1);return self}var builder=[];var builderChanges=[];for(var i=0;i<length;i++){var doc=arr[i];if(typeof doc.json===UNDEFINED){builder.push(doc);if(changes)builderChanges.push(changes);continue}builder.push(doc.json);if(doc.changes)builderChanges.push(doc.changes)}if(builder.length===0){self.next();return}self.emit("insert",true,builder.length);self.status=STATUS_WRITING;self.countWrite++;appendFile(self.filename,builder,function(){self.countWrite--;self.emit("insert",false,builder.length);self.next();self.changelog.insert(builderChanges);if(fnCallback){var length=builder.length;setImmediate(function(){fnCallback(length)})}builder=null;builderChanges=null;arr=null;var keys=Object.keys(self.meta.views);var length=keys.length;for(var i=0;i<length;i++)self.views.refresh(keys[i])},self);return self};Database.prototype.read=function(fnMap,fnCallback,itemSkip,itemTake,isScalar,name){var self=this;var skip=itemSkip||0;var take=itemTake||0;if(self.status===STATUS_LOCKING||self.status===STATUS_PENDING||self.countRead>=MAX_READSTREAM){self.pendingRead.push(function(){self.read(fnMap,fnCallback,itemSkip,itemTake,isScalar)});return self}if(typeof fnCallback===UNDEFINED){fnCallback=fnMap;fnMap=function(doc){return doc}}if(typeof fnMap===STRING)fnMap=filterPrepare(fnMap);if(fnMap===null)fnMap=function(doc){return doc};self.emit(name||"read",true,0);self.countRead++;self.status=STATUS_READING;var selected=[];var current="";var count=0;var resume=true;var fnBuffer=function(buffer){current+=buffer;return current};var fnItem=function(err,doc){if(!resume)return;current="";if(err)return;var item=fnMap(doc);if(item===false||item===null||typeof item===UNDEFINED)return;count++;if(skip>0&&count<=skip)return;if(!isScalar)selected.push(item===true?doc:item);if(take>0&&selected.length===take)resume=false};var reader=self.file.open(self.filename,MAX_BUFFER_SIZE,function(buffer){onBuffer(buffer,fnItem,fnBuffer);return resume},function(){self.countRead--;self.next();setImmediate(function(){self.emit(name||"read",false,isScalar?count:selected.length);fnCallback(isScalar?count:selected)})});return self};Database.prototype.all=function(fnMap,fnCallback,itemSkip,itemTake){return this.read(fnMap,fnCallback,itemSkip,itemTake,false,"all")};Database.prototype.one=function(fnMap,fnCallback){var cb=function(selected){fnCallback(selected[0]||null)};return this.read(fnMap,cb,0,1,false,"one")};Database.prototype.top=function(max,fnMap,fnCallback){return this.read(fnMap,fnCallback,0,max,false,"top")};Database.prototype.count=function(fnFilter,fnCallback){return this.read(fnFilter,fnCallback,0,0,true,"count")};Database.prototype.each=function(fnDocument,fnCallback){var self=this;if(self.status===STATUS_LOCKING||self.status===STATUS_PENDING||self.countRead>=MAX_READSTREAM){if(fnDocument)self.pendingEach.push({item:fnDocument,callback:fnCallback});return self}var operation=[];if(fnDocument)operation.push({item:fnDocument,callback:fnCallback});var length=self.pendingEach.length;for(var i=0;i<length;i++)operation.push(self.pendingEach[i]);if(operation.length===0){self.next();return self}self.countRead++;self.status=STATUS_READING;var current="";var count=0;self.pendingEach=[];var fnBuffer=function(buffer){current+=buffer;return current};var fnItem=function(err,doc){current="";if(err){self.emit("error",err,"each-buffer");return}var length=operation.length;for(var i=0;i<length;i++){try{operation[i].item(doc,count,"each-buffer")}catch(e){self.emit("error",e)}}count++};self.emit("each",true,0);var reader=self.file.open(self.filename,MAX_BUFFER_SIZE,function(buffer){onBuffer(buffer,fnItem,fnBuffer);return true},function(){self.countRead--;self.next();setImmediate(function(){self.emit("each",false,count);var length=operation.length;for(var i=0;i<length;i++){var fn=operation[i];if(fn.callback)fn.callback()}})});return self};Database.prototype.sort=function(fnMap,fnSort,itemSkip,itemTake,fnCallback){var self=this;var selected=[];var count=0;if(typeof fnMap===STRING)fnMap=filterPrepare(fnMap);itemTake=itemTake||30;itemSkip=itemSkip||0;var onCallback=function(){selected.sort(fnSort);if(itemSkip>0||itemTake>0)selected=selected.slice(itemSkip,itemSkip+itemTake);fnCallback(selected,count)};var onItem=function(doc){var item=fnMap(doc);if(item===false||item===null||typeof item===UNDEFINED)return;count++;selected.push(item===true?doc:item)};self.each(onItem,onCallback);return self};Database.prototype.clear=function(fnCallback,changes){var self=this;var type=typeof fnCallback;if(type===UNDEFINED)fnCallback=null;if(type===STRING){changes=fnCallback;fnCallback=null}self.pendingClear.push(function(){if(changes)self.changelog.insert(changes);if(fnCallback)fnCallback()});if(self.status!==STATUS_UNKNOWN)return self;self.status=STATUS_LOCKING;var operation=[];var length=self.pendingClear.length;for(var i=0;i<length;i++){var fn=self.pendingClear[i];if(fn!==null)operation.push(fn)}self.emit("clear",true,false);self.pendingClear=[];fs.exists(self.filename,function(exists){if(!exists){self.next();setImmediate(function(){self.emit("clear",false,true);var length=operation.length;for(var i=0;i<length;i++){var fn=operation[i];if(fn)fn()}});return}fs.unlink(self.filename,function(err){if(err)self.emit("error",err,"clear");self.next();setImmediate(function(){self.emit("clear",false,err===null);var length=operation.length;for(var i=0;i<length;i++){var fn=operation[i];if(fn)fn()}})})});return self};Database.prototype.drop=function(fnCallback){var self=this;if(typeof fnCallback===UNDEFINED)fnCallback=null;self.pendingDrop.push(fnCallback);if(self.status!==STATUS_UNKNOWN)return self;self.status=STATUS_LOCKING;var operation=[];self.pendingDrop.forEach(function(o){if(o!==null)operation.push(o)});self.emit("drop",true,false);self.pendingDrop=[];self._drop();fs.exists(self.filename,function(exists){if(!exists){self.next();setImmediate(function(){self.emit("drop",false,true);operation.forEach(function(fn){if(fn)fn()})});return}fn.unlink(self.filenameMeta,noop);fs.unlink(self.filename,function(err){if(err)self.emit("error",err,"drop");self.next();setImmediate(function(){self.emit("drop",false,err===null);operation.forEach(function(fn){if(fn)fn(err===null)})})})});return self};function noop(){}Database.prototype._drop=function(){var self=this;fs.readdirSync(self.directory).forEach(function(filename){var isView=filename.indexOf(self.name+"#")!==-1&&filename.indexOf(EXTENSION_VIEW)!==-1;if(isView){fs.unlink(path.join(self.directory,filename),noop);return}var isChange=self.name+EXTENSION_CHANGES===filename;if(isChange){fs.unlink(path.join(self.directory,filename),noop);return}});if(self.binary===null)return self;fs.readdirSync(self.binary.directory).forEach(function(filename){if(filename.indexOf(self.name+"#")===-1||filename.indexOf(EXTENSION_BINARY)===-1)return;fs.unlink(path.join(self.binary.directory,filename),noop)});return self};Database.prototype.update=function(fnUpdate,fnCallback,changes,type){var self=this;if(typeof fnCallback===STRING){changes=fnCallback;fnCallback=null}if(typeof fnUpdate!==UNDEFINED)self.pendingLock.push(updatePrepare(fnUpdate,fnCallback,changes,type||"update"));if(self.status!==STATUS_UNKNOWN){return self}var operation=[];self.pendingLock.forEach(function(fn){operation.push(fn)});if(operation.length===0){self.next();return self}self.status=STATUS_LOCKING;var current="";var operationLength=operation.length;var lines=[];var countRemove=0;var countUpdate=0;var countWrite=0;var completed=false;self.emit("update/remove",true,0,0);self.pendingLock=[];var fnRename=function(){operation.forEach(function(o){if(o.type==="update"){o.count=countUpdate;return}if(o.type==="remove")o.count=countRemove});fs.rename(self.filenameTemp,self.filename,function(err){if(err)self.emit("error",err,"update/rename-file");self.emit("update/remove",false,countUpdate,countRemove);var changes=[];operation.forEach(function(o){if(typeof o.changes!==UNDEFINED)changes.push(o.changes);if(o.callback)(function(cb,count){setImmediate(function(){cb(count)})})(o.callback,o.count)});if(changes.length>0)self.changelog.insert(changes);self.next()})};var fnWrite=function(json,valid){if(lines.length>25||valid){if(lines.length===0){if(completed&&countWrite<=0)fnRename();return}countWrite++;fs.appendFile(self.filenameTemp,lines.join(NEWLINE)+NEWLINE,function(){countWrite--;if(completed&&countWrite<=0)fnRename()});lines=[]}if(typeof json===STRING)lines.push(json)};var fnBuffer=function(buffer){current+=buffer;return current};var fnItem=function(err,doc,json){current="";var skip=false;var value=null;for(var i=0;i<operationLength;i++){var fn=operation[i];value=fn.filter(doc)||null;if(value===null)break}if(value===null){self.emit("remove",doc);countRemove++;return}var updated=JSON.stringify(value);if(updated!==json){self.emit("update",value);countUpdate++}fnWrite(updated)};fs.appendFile(self.filenameTemp,"");var reader=self.file.open(self.filename,MAX_BUFFER_SIZE,function(buffer){onBuffer(buffer.toString(),fnItem,fnBuffer);return true},function(success){if(!success){self.next();return}completed=true;fnWrite(null,true)});return self};Database.prototype.prepare=function(fnUpdate,fnCallback,changes){var self=this;if(typeof fnUpdate!==UNDEFINED)self.pendingLock.push(updatePrepare(fnUpdate,fnCallback,changes,"update"));return self};Database.prototype.remove=function(fnFilter,fnCallback,changes){var self=this;if(typeof fnFilter===STRING)fnFilter=filterPrepare(fnFilter);var filter=function(item){if(fnFilter(item)===true)return null;return item};self.update(filter,fnCallback,changes,"remove");return self};Database.prototype.pause=function(){var self=this;if(self.isPending===true)return self;self.isPending=true;if(self.status===STATUS_UNKNOWN){self.status=STATUS_PENDING;self.emit("pause/resume",true)}return self};Database.prototype.resume=function(){var self=this;if(!self.isPending)return self;self.isPending=false;self.emit("pause/resume",false);self.next();return self};Database.prototype.next=function(){var self=this;if(self.isPending){if(self.status!==STATUS_PENDING){self.status=STATUS_PENDING;self.emit("pause")}return}self.status_prev=self.status;self.status=STATUS_UNKNOWN;if(self.countRead>0){self.status=STATUS_READING;return}if(self.countWrite>0){self.status=STATUS_WRITING;return}if(self.pendingWrite.length>0){self.insert(self.pendingWrite);self.pendingWrite=[];return}if(self.pendingLock.length>0){self.update();return}if(self.pendingEach.length>0){self.each();return}if(self.pendingRead.length>0){var max=self.pendingRead.length;if(max>MAX_READSTREAM)max=MAX_READSTREAM;for(var i=0;i<max;i++)self.pendingRead.shift()();return}if(self.pendingDrop.length>0){self.drop();return}if(self.pendingClear.length>0){self.clear();return}setImmediate(function(){self.emit("complete",self.status_prev)})};Database.prototype.description=function(value){var self=this;if(typeof value===UNDEFINED)return self.meta.description;self.meta.description=(value||"").toString();self._metaSave();return self};Database.prototype.custom=function(value){var self=this;if(typeof value===UNDEFINED)return self.meta.custom;self.meta.custom=value;self._metaSave();return self};Database.prototype._metaSave=function(){var self=this;if(typeof self.meta.created===UNDEFINED)self.meta.created=new Date;fs.writeFile(self.filenameMeta,JSON.stringify(self.meta),noop);return self};Database.prototype._metaLoad=function(callback){var self=this;fs.readFile(self.filenameMeta,function(err,data){var isReady=self.isReady;self.isReady=true;if(err){if(!isReady){self.emit("ready");self.emit("load")}if(callback)callback(false,self.meta);return}self.meta=JSON.parse(data.toString("utf8"));var keys=Object.keys(self.meta.views);var length=keys.length;for(var i=0;i<length;i++)self.meta.views[keys[i]].isReady=true;if(!isReady){self.emit("ready");self.emit("load")}if(callback)callback(true,self.meta)});return self};Views.prototype.all=function(name,fnCallback,itemSkip,itemTake,fnMap){var self=this;var view=self.views[name];if(typeof view===UNDEFINED){view=self.getView(name);self.views[name]=view}var type=typeof itemSkip;if(type===FUNCTION||type===STRING){fnMap=itemSkip;itemSkip=0;itemTake=0}else{type=typeof itemTake;if(type===FUNCTION||type===STRING){fnMap=itemTake;itemTake=0}}if(typeof fnMap===STRING)fnMap=filterPrepare(fnMap);if(typeof fnMap!==FUNCTION)fnMap=function(o){return o};view.read(fnMap,fnCallback,itemSkip,itemTake);return self.db};Views.prototype.top=function(name,top,fnCallback,fnMap){var self=this;var view=self.views[name];if(typeof view===UNDEFINED){view=self.getView(name);self.views[name]=view}if(typeof fnMap===STRING)fnMap=filterPrepare(fnMap);if(typeof fnMap!==FUNCTION)fnMap=function(o){return o};view.read(fnMap,fnCallback,0,top,true);return self.db};Views.prototype.one=function(name,fnMap,fnCallback){var self=this;var view=self.views[name];if(typeof view===UNDEFINED){view=self.getView(name);self.views[name]=view}if(typeof fnCallback===UNDEFINED){fnCallback=fnMap;fnMap=null}if(typeof fnMap===STRING)fnMap=filterPrepare(fnMap);if(typeof fnMap!==FUNCTION)fnMap=function(o){return o};view.read(fnMap,fnCallback,0,1,true);return self.db};Views.prototype.drop=function(name,fnCallback,changes){var self=this;var view=self.views[name];if(typeof fnCallback===STRING){changes=fnCallback;fnCallback=null}if(typeof view===UNDEFINED){view=self.getView(name);self.views[name]=view}delete self.db.meta.views[name];self.db._metaSave();self.db.emit("view/drop",true,name);view.operation(function(cb){fs.exists(view.filename,function(exists){self.db.emit("view/drop",false,name);if(changes)self.db.changelog.insert(changes);if(!exists){if(fnCallback)fnCallback(true);if(cb)cb();return}fs.unlink(view.filename,function(err){if(err)self.db.emit("error",err,"view/drop");if(fnCallback)fnCallback(true);if(cb)cb()})})});return self.db};Views.prototype.refresh=function(name,fnCallback){var self=this;var schema=self.db.meta.views[name];schema.isReady=false;var fnSort=schema["sort"]||"";var fnMap=schema["map"];if(fnSort.length===0)fnSort=null;else fnSort=eval("("+fnSort+")");fnMap=eval("("+fnMap+")");var selected=[];var count=0;self.db.emit("view/refresh",true,name,"");var onCallback=function(){if(fnSort)selected.sort(fnSort);var view=self.views[name];if(typeof view===UNDEFINED){view=self.getView(name);self.views[name]=view}var filename=self.getFileName(name);view.operation(function(cb){var fnAppend=function(){appendFile(filename,selected,function(){self.db.emit("view/refresh",false,name,count);schema.isReady=true;if(fnCallback)setImmediate(function(){fnCallback(count)});if(cb)cb()},self.db)};fs.exists(filename,function(exists){if(!exists){fnAppend();return}fs.unlink(filename,function(err){if(!err){fnAppend();return}self.db.emit("error",err,"view/refresh");if(cb)cb()})})})};var onItem=function(doc){var item=fnMap(doc)||null;if(item===null)return;count++;selected.push(item)};self.db.each(onItem,onCallback)};Views.prototype.create=function(name,fnMap,fnSort,fnCallback,changes){var self=this;if(typeof fnCallback===STRING){changes=fnCallback;fnCallback=null}if(typeof fnMap===STRING)fnMap=filterPrepare(fnMap);self.db.meta.views[name]={map:fnMap.toString(),sort:(fnSort||"").toString(),isReady:false};self.db._metaSave();self.db.emit("view/create",true,name,0);if(changes)self.db.changelog.insert(changes);self.refresh(name,fnCallback);return self};Views.prototype.getView=function(name){var self=this;return new View(self.db,name,self.getFileName(name))};Views.prototype.getFileName=function(name){var self=this;return path.join(self.directory,self.db.name+"#"+name+EXTENSION_VIEW)};View.prototype.read=function(fnMap,fnCallback,itemSkip,itemTake,skipCount,isScalar){var self=this;var skip=itemSkip||0;var take=itemTake||0;skipCount=skipCount||false;if(self.status===STATUS_LOCKING||self.countRead>=MAX_READSTREAM){self.pendingRead.push(function(){self.read(fnMap,fnCallback,itemSkip,itemTake,isScalar)});return self}self.status=STATUS_READING;if(typeof fnMap===STRING)fnMap=filterPrepare(fnMap);if(fnMap===null)fnMap=function(o){return o};self.db.emit("view",true,self.name,0);self.countRead++;var selected=[];var current="";var count=0;var resume=true;var fnBuffer=function(buffer){current+=buffer;return current};var fnItem=function(err,doc){if(!resume)return;current="";if(err)return;var item=fnMap(doc);if(item===false||item===null||typeof item===UNDEFINED)return;count++;if(skip>0&&count<=skip)return;if(!isScalar)selected.push(item===true?doc:item);if(take>0&&selected.length===take)resume=false};var reader=self.file.open(self.filename,MAX_BUFFER_SIZE,function(buffer){if(skipCount&&!resume){count=-1;return false}onBuffer(buffer,fnItem,fnBuffer);return resume},function(){self.countRead--;self.next();setImmediate(function(){self.emit("view",false,self.name,count);fnCallback(selected,count)})});return self};View.prototype.operation=function(fnCallback){var self=this;if(typeof fnCallback!==UNDEFINED)self.pendingOperation.push(fnCallback);if(self.status!==STATUS_UNKNOWN)return self;self.status=STATUS_LOCKING;var operation=self.pendingOperation.shift();operation(function(){self.next()});return self};View.prototype.next=function(){var self=this;self.status=STATUS_UNKNOWN;if(self.countRead>0){self.status=STATUS_READING;return}if(self.pendingOperation.length>0){self.operation();return}if(self.pendingRead.length>0){var max=self.pendingRead.length;if(max>MAX_READSTREAM)max=MAX_READSTREAM;for(var i=0;i<max;i++)self.pendingRead.shift()();return}};Stored.prototype.create=function(name,fn,fnCallback,changes){if(typeof fnCallback===STRING){var tmp=changes;changes=fnCallback;fnCallback=changes}var self=this;self.db.meta.stored[name]=fn.toString();self.db._metaSave(fnCallback);delete self.cache[name];if(changes)self.db.changelog.insert(changes);self.db.emit("stored/create",name);return self.db};Stored.prototype.remove=function(name,fnCallback,changes){var self=this;if(typeof fnCallback===STRING){var tmp=changes;changes=fnCallback;fnCallback=changes}if(changes)self.db.changelog.insert(changes);delete self.cache[name];delete self.db.meta.stored[name];self.db._metaSave(fnCallback);return self.db};Stored.prototype.clear=function(fnCallback,changes){var self=this;if(typeof fnCallback===STRING){var tmp=changes;changes=fnCallback;fnCallback=changes}if(changes)self.db.changelog.insert(changes);self.cache={};self.db.meta.stored={};self.db._metaSave(fnCallback);return self.db};Stored.prototype.execute=function(name,params,fnCallback,changes){var self=this;var type=typeof params;if(type===FUNCTION){changes=fnCallback;fnCallback=params;params=null}if(typeof fnCallback===STRING){var tmp=changes;changes=fnCallback;fnCallback=tmp}if(changes)self.db.changelog.insert(changes);var fn=self.db.meta.stored[name];if(typeof fn===UNDEFINED){if(fnCallback)fnCallback();return}var cache=self.cache[name];self.db.emit("stored",name);if(typeof fn===UNDEFINED){if(fnCallback)fnCallback();return}if(typeof cache===UNDEFINED){fn=eval("("+fn+")");self.cache[name]=fn}else fn=cache;if(typeof fnCallback===UNDEFINED)fnCallback=function(){};fn.call(self.db,self.db,fnCallback,params||null);return self};Binary.prototype.insert=function(name,type,buffer,fnCallback,changes){if(typeof buffer===STRING)buffer=new Buffer(buffer,"base64");if(typeof fnCallback===STRING){changes=fnCallback;fnCallback=null}var self=this;var size=buffer.length;var dimension={width:0,height:0};if(name.indexOf(".gif")!==-1)dimension=dimensionGIF(buffer);else if(name.indexOf(".png")!==-1)dimension=dimensionPNG(buffer);else if(name.indexOf(".jpg")!==-1)dimension=dimensionJPG(buffer);var header=new Buffer(BINARY_HEADER_LENGTH);header.fill(" ");header.write(JSON.stringify({name:name,size:size,type:type,width:dimension.width,height:dimension.height}));var id=(new Date).getTime().toString()+Math.random().toString(36).substring(10);var key=self.db.name+"#"+id;var stream=fs.createWriteStream(path.join(self.directory,key+EXTENSION_BINARY));stream.write(header,"binary");stream.end(buffer);stream=null;if(changes)self.db.changelog.insert(changes);if(fnCallback)fnCallback(id,header);return id};Binary.prototype.update=function(id,name,type,buffer,fnCallback,changes){if(typeof buffer===STRING)buffer=new Buffer(buffer,"base64");if(typeof fnCallback===STRING){changes=fnCallback;fnCallback=null}var self=this;var size=buffer.length;var dimension={width:0,height:0};var key=id;if(key.indexOf("#")===-1)key=self.db.name+"#"+key;if(name.indexOf(".gif")!==-1)dimension=dimensionGIF(buffer);else if(name.indexOf(".png")!==-1)dimension=dimensionPNG(buffer);else if(name.indexOf(".jpg")!==-1)dimension=dimensionJPG(buffer);var header=new Buffer(BINARY_HEADER_LENGTH);header.fill(" ");header.write(JSON.stringify({name:name,size:size,type:type,width:dimension.width,height:dimension.height}));var stream=fs.createWriteStream(path.join(self.directory,key+EXTENSION_BINARY));stream.write(header,"binary");stream.end(buffer);stream=null;if(changes)self.db.changelog.insert(changes);if(fnCallback)fnCallback(id,header);return id};Binary.prototype.read=function(id,callback){var self=this;if(id.indexOf("#")===-1)id=self.db.name+"#"+id;var filename=path.join(self.directory,id+EXTENSION_BINARY);var stream=fs.createReadStream(filename,{start:0,end:BINARY_HEADER_LENGTH-1,encoding:"binary"});stream.on("error",function(err){callback(err,null,null)});stream.on("data",function(buffer){var json=new Buffer(buffer,"binary").toString("utf8").replace(/^[\s]+|[\s]+$/g,"");stream=fs.createReadStream(filename,{start:BINARY_HEADER_LENGTH});callback(null,stream,JSON.parse(json))});return self.db};Binary.prototype.remove=function(id,fnCallback,changes){var self=this;var key=id;if(key.indexOf("#")===-1)key=self.db.name+"#"+key;var filename=path.join(self.directory,key+EXTENSION_BINARY);if(typeof fnCallback===STRING){changes=fnCallback;fnCallback=null}fs.exists(filename,function(exists){if(changes)self.db.changelog.insert(changes);if(!exists){if(fnCallback)fnCallback(false);return}fs.unlink(filename,function(){if(fnCallback)fnCallback(true)})});return self.db};Changelog.prototype.insert=function(description){var self=this;if(!self.db.changes)return self.db;if(typeof description===UNDEFINED)return self.db;if(!(description instanceof Array))description=[description||""];if(description.length===0)return self.db;var lines="";var dd=new Date;var y=dd.getFullYear();var M=(dd.getMonth()+1).toString();var d=dd.getDate().toString();var h=dd.getHours().toString();var m=dd.getMinutes().toString();var s=dd.getSeconds().toString();if(M.length===1)M="0"+M;if(d.length===1)d="0"+d;if(m.length===1)m="0"+m;if(h.length===1)h="0"+h;if(s.length===1)s="0"+s;var dt=y+"-"+M+"-"+d+" "+h+":"+m+":"+s;description.forEach(function(line){lines+=dt+" | "+line+NEWLINE;self.db.emit("change",line)});fs.appendFile(self.filename,lines,function(err){});return self.db};Changelog.prototype.read=function(fnCallback){var self=this;fs.exists(self.filename,function(exist){if(!exist){fnCallback([]);return}fs.readFile(self.filename,function(err,data){if(err){fnCallback([]);return}var lines=data.toString("utf8").split("\n");if(lines[lines.length-1]==="")lines.pop();fnCallback(lines)})});return self.db};Changelog.prototype.clear=function(fnCallback){var self=this;fs.exists(self.filename,function(exist){if(!exist){if(fnCallback)fnCallback(false);return}fs.unlink(self.filename,function(err,data){if(err){if(fnCallback)fnCallback(false);return}if(fnCallback)fnCallback(true)})});return self.db};FileReader.prototype.open=function(filename,size,fnBuffer,fnCallback){var self=this;fs.open(filename,"r",function(err,fd){if(err){fnCallback(false);return}size=size||1024;var next=function next(cancel,position){if(cancel){fs.close(fd);fd=null;fnCallback(true);return}self.read(fd,position+size,size,fnBuffer,next)};self.read(fd,0,size,fnBuffer,next)})};FileReader.prototype.read=function(fd,position,size,fnBuffer,next){var buffer=new Buffer(size);fs.read(fd,buffer,0,size,position,function(err,num){var cancel=num!==size;var data=buffer.toString("utf8",0,num);if(cancel){fnBuffer(data);next(true);return}try{cancel=!fnBuffer(data)}catch(err){cancel=true}setImmediate(function(){next(cancel,position,size)})})};function appendFile(filename,arr,fnCallback,db){if(arr.length===0){fnCallback();return}var lines="";arr.slice(0,30).forEach(function(o){lines+=JSON.stringify(o)+NEWLINE});fs.appendFile(filename,lines,function(err){if(err)db.emit("error",err);appendFile(filename,arr.slice(30),fnCallback,db)})}function filterPrepare(fnFilter){if(fnFilter.length===0)return function(){return true};return eval("(function(doc){"+(fnFilter.indexOf("return ")===-1?"return ":"")+fnFilter+"})")}function onBuffer(buffer,fnItem,fnBuffer){var index=buffer.indexOf(NEWLINE);if(index===-1){fnBuffer(buffer);return}var json=fnBuffer(buffer.substring(0,index));try{fnItem(null,JSON.parse(json),json)}catch(ex){fnItem(ex,null,json)}onBuffer(buffer.substring(index+1),fnItem,fnBuffer)}function updatePrepare(fnUpdate,fnCallback,changes,type){if(typeof fnUpdate===STRING)fnUpdate=filterPrepare(fnUpdate);return{filter:fnUpdate,callback:fnCallback,count:0,type:type,changes:changes}}var sof={192:true,193:true,194:true,195:true,197:true,198:true,199:true,201:true,202:true,203:true,205:true,206:true,207:true};function u16(buf,o){return buf[o]<<8|buf[o+1]}function u32(buf,o){return buf[o]<<24|buf[o+1]<<16|buf[o+2]<<8|buf[o+3]}function dimensionGIF(buffer){return{width:buffer[6],height:buffer[8]}}function dimensionJPG(buffer){var len=buffer.length;var o=0;var jpeg=255==buffer[0]&&216==buffer[1];if(!jpeg)return;o+=2;while(o<len){while(255!=buffer[o])o++;while(255==buffer[o])o++;if(!sof[buffer[o]]){o+=u16(buffer,++o);continue}var w=u16(buffer,o+6);var h=u16(buffer,o+4);return{width:w,height:h}}}function dimensionPNG(buffer){return{width:u32(buffer,16),height:u32(buffer,16+4)}}exports.database=Database;exports.load=exports.open=exports.nosql=exports.init=function(filename,directory,changes){return new Database(filename,directory,changes)};
Example #16
0
 server.on('connection', function(sock) {
   var log = new Date() + ' >> ' + sock.remoteAddress;
   fs.appendFile('log.txt', log, function (err) { });
   console.log(log);
 });
Example #17
0
function writeToLog(logFileName, message) {
  if (typeof message == "object") {message = JSON.stringify(message);}
  message = new Date().toString() + "\n" + message;
  fs.appendFile(logFileName, message + "\n", logError);
}
Example #18
0
app.post('/api', function (req, res) {
	global.api= req.body.api;
	console.log(global.api);
	res.send('{ok2}');



// build page ---------------------------

	function puts(error, stdout, stderr ){sys.puts(stdout)}
	exec("bash newinstance.sh",puts);
	
//	var tech_array = global.tech
//	for (var i=0; i<global.tech_len; i++ ){
//	    exec("./" + global.tech[i] + ".sh",puts);
//	}
	


	//prepare index.html ------------------------------

	// d3
	if (include(global.api,"D3")) {
		var d3 = "\n\t<script src=\"http://d3js.org/d3.v3.min.js\" charset=\"utf-8\"></script>"
		fs.appendFile(__dirname + "/package/index.html", d3, function(err, fd){
			if(err) {
				console.log(err);
			} else {
				console.log(fd + " d3 tags added successfully.");
			}
		});
	}
	
	// insert </head> <body>
	fs.appendFile(__dirname + "/package/index.html", '\n</head>\n<body>\n\
	\t<h1>Hello World!<h1>', function(err, fd){
		if(err) {
			console.log(err);
		} else {
			console.log(fd + " /head, body tags added successfully.");
		}
	});

    if (include(global.api,"Google Analytics")) {
		// goog analytics boiler plate
		var goog = " \
		\n\t<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. --> \n\
		\t<script>\n\
			\tvar _gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']];\n\
			\t(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];\n\
			\tg.src='//www.google-analytics.com/ga.js';\n\
			\ts.parentNode.insertBefore(g,s)}(document,'script'));\n\
		\t</script>"

		fs.appendFile(__dirname + "/package/index.html", goog, function(err, fd){
			if(err) {
				console.log(err);
			} else {
				console.log(fd + " google analytics snippet added successfully.");
			}
		});
	}
	
	// final tags
	fs.appendFile(__dirname + "/package/index.html", '\n</body>\n</html>', function(err, fd){
		if(err) {
			console.log(err);
		} else {
			console.log(fd + " end tags added successfully.");
		}
	});

	// scp package over to the new server
    //exec("scp -r package/ user@server:~/",puts);
});
Example #19
0
var debug = function (contents) {
  fs.appendFile(updateLogPath, new Date().toISOString() + ' - ' + contents + os.EOL)
}
Example #20
0
 
//Ro is initialized to 10 kilo ohms
var           MQ2_Ro           =  9.7; //valor medido experimentalmente
var           MQ3_Ro           =  175; //valor medido experimentalmente
var           MQ4_Ro           =  25.5; //valor medido experimentalmente
var           MQ6_Ro           =  5.68; //valor medido experimentalmente


var fs =require('fs');
var dateformat = require('date-format');
var date = new Date() ;

var fileName = "logs/"+ dateformat.asString('yyyyMMddhhmm',date) 
  + ".csv";
fs.appendFile(fileName, 'date,A0,A1,A2,A3,A4,A5,H,T\n', function (err) {
  if (err) throw err;
  console.log('The "data to append" was appended to file!');
});
var timeStamp;
var dataLog = false;
var logInterval = 1000 * 2; //1000 * X segundos
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
Example #21
0
/*
* create a new file with appendFile
*/
var fs = require('fs');

fs.appendFile('mynewfile1.txt', 'Hello content!', function (err) {
  if (err) throw err;
  console.log('Saved!'+"\n");
});
Example #22
0
				exec('launchctl unload '+this.plist,{},function(){
					fs.appendFile(me.outlog,'\n'+new Date().toLocaleString()+' - '+me.name+' Stopped');
					me.emit('stop');
					callback && callback();
				});
Example #23
0
var copyFile = function(name, buffer){
    fs.appendFile(name, buffer);
}
Example #24
0
var dataCollector = function (data) {
  var demo = data.demo;
  fs.appendFile('data.txt', prettyjson.render(JSON.stringify(demo)));
  fs.appendFile('data.txt', "\n\n");
};
Example #25
0
 app.get('/mailing-list', function( req, res ) {
     fs.appendFile( 'emails.txt', req.query['email'] + "\n", function(err) { return; });
     res.send(200);
 });
Example #26
0
function writeIconCSS() {
        fs.appendFile('config/custom.css', selectors);
}
Example #27
0
  function(data, callback) {
    console.log('Data from a file: ', data.toString());

    // Append data to our file
    fs.appendFile(FILE_NAME, 'our sweety string\n', callback);
  }
Example #28
0
		  $("div div div div div div div div .story-body p").each(function(element) {
			//console.log(myfile);
			var paragraph = $(this);
			var text = "\n"+paragraph.text()+"\n";
			fs.appendFile("Articles/CBC/CBC_"+myfile, text, function (err) {});
		  });
 createMessage(request, function(message){
   messages.push(message);
   fs.appendFile('./messages.txt', JSON.stringify(message) + '\n');
   message.objectId = ++objectId;
   sendResponse(response, {objectId: 1}, 201);
 });
Example #30
0
/**
 * 纪录edp的运行历史
 * 
 * @inner
 */
function saveCommandHistory() {
    var fs = require('fs');
    var historyFile = require('./edp').getConfig('.edp_history');
    var commandLog = '[' + new Date() + ']: ' + process.argv.join(' ') + '\n';
    fs.appendFile(historyFile, commandLog);
}