working on it ...

Filters

Explore Public Snippets

Sort by

Found 17k snippets matching: node

    public by micurs modified Mar 4, 2014  6863148  307  9  18

    Typescript: passing a class member function as parameter to another function

    Typescript introduces the class construct and the concept of member functions. However if you try to pass a instance member function as parameter to another function the binding with the instance is lost. To solve this problem you can use the capability of javascript (and Typescript) to support closures on anonymous function (or lambda expressio
    ///<reference path='../types/node.d.ts'/>
    ///<reference path='../types/underscore.d.ts'/>
    
    import _ = require("underscore");
    
    class SomePeople {
      values : string[] = [ 'John', 'Mary', 'Peter'];
    
      out() {
        _.each( this.values, (v) => process.stdout.write( v + '\n') );
      }
    }
    // This function accept a function it will execute internally
    function outSomething( outFunc : () => any ) {
      outFunc();
    }
    
    var crowd = new SomePeople();
    
    // This won't work since the actual crowd instance binding will be lost
    outSomething( crowd.out );
    
    // This will work: the closure within the lambda expression retain the
    // crowd instance and its data
    outSomething( () => crowd.out() );
        

    public by sTiLL-iLL @ SniPitz-KND modified Dec 15, 2014  443992  2  8  24

    Signals.js... A fast and efficient event system in javascript.

    Signals.js... A fast and efficient event system in javascript.: Signals.js
    // Signalz.js
    
    var Signals = (function () {
    	'use strict';
    	var sigCache = {},
    	addReceiver = function(eventName, func) {
    		return wen(eventName, function(evnt){
    			return func(evnt);
    		});
    	},
    	signalReceived = function(eventName, func) {
    		return wen(eventName, function(evnt){
    			return func(evnt);
    		});
    	},
    	dropReceivers = function (eventName) {
    		if (!eventName) {
    			sigCache = {};
    			return this;
    		}
    		if (sigCache && sigCache[eventName]) {
    			sigCache[eventName] = null;
    		}
    		return this;
    	},    
    	signalOnce = function (eventName, func) {
    		var slf = this;
    		setSingleRV(true);
    		function onit () {
    			dropReceiver(eventName, wen);
    			func.apply(this, arguments);
    		};
    		wen.receiver = onit;	
    		return this;
    	},
    	dropReceiver = function (eventName, func) {
    		if (sigCache && sigCache[eventName]) {
    			var sigLst = sigCache[eventName];	
    			if (isAry(sigLst)) {
    				var idx = -1;
    				for (var i = 0, l = sigLst.length; i < l; i++) {
    					if (sigLst[i] === func || (sigLst[i].receiver && sigLst[i].receiver === func)) {
    						idx = i;
    						break;
    					}
    				}
    				if (idx < 0) {
    					return this;
    				}
    				sigLst.splice(idx, 1);
    				if (!sigLst.length) {
    					delete sigCache[eventName];
    				}
    			} 
    			else if (sigLst === func || (sigLst.receiver && sigLst.receiver === func)) {
    				delete sigCache[eventName];
    			}
    		}
    		return this;
    	},  
    	setSingleRV = function (val) {
    		singleRtnVal = val;
    		return this;
    	},  
    	getSingleRV = function() {
    		if (receivers.hasOwnProperty('singleRtnVal')) {
    			return singleRtnVal;
    		}
    		else {
    			return true;
    		}
    	},	 
    	castSignal = function(eventName, args) {
    		var recvrLst = receiverObjects(eventName),
    		k, recvr, i, rspns;
    		for (k in recvrLst ) {
    			if (recvrLst.hasOwnProperty(k)) {
    				i = recvrLst[k].length;		
    				while (i--) {
    					recvr = recvrLst[k][i];
    					if (recvr.signalOnce === true) {
    						dropReceiver(eventName, recvr);
    					}	
    					rspns = recvr.call(this, args || []);
    					if (rspns === getSingleRV()) {
    						dropReceiver(eventName, recvr);
    					}
    				}
    			}
    		}
    	 	return this;
      	};
    	function isAry(obj) {
    		return (obj.constructor === Array);
    	};
    	function receiverObjects(eventName) {
    		var recvrLst = receivers(eventName), rspns;	
    		if (isAry(recvrLst)) {
    			rspns = {};
    			rspns[eventName] = recvrLst;
    		}	
    		return rspns || recvrLst;
    	};
    	function receivers(eventName) {
    		if (!sigCache) {
    			sigCache = {};
    		}
    		if (!sigCache[eventName]) {
    			sigCache[eventName] = [];
    		}
    		if (!isAry(sigCache[eventName])) {
    			sigCache[eventName] = [sigCache[eventName]];
    		}
    		return sigCache[eventName];
    	};
    	function wen(eventName, func) {
    		if (!sigCache) {
    			sigCache = {};
    		}
    		if (!sigCache[eventName]) {
    			sigCache[eventName] = func;
    		} 
    		else if (isArry(sigCache[eventName])) {
    			sigCache[eventName].push(func);
    		} 
    		else {
    			sigCache[eventName] = [sigCache[eventName], func];
    		}	
    		return;
    	};
    	return {
    		signal: castSignal,
    		signaled: signalReceived,
    		receive: addReceiver,
    		receiveOnce: signalOnce,
    		signaledOnce: signalOnce,
    		dropReceiver: dropReceiver,
    		assignReceiver: addReceiver,
    		receivers: receivers,
    		dropReceivers: dropReceivers
    	};
    }());
    
    exports.Signals = Signals;
    
    
                

    public by sTiLL-iLL modified Dec 27, 2014  307526  0  5  14

    my nonblocking, threadsafe file writer/appender for nodejs. works great with clustered servers, and child processes that write to shared or static file-stores

    my nonblocking, threadsafe file writer/appender for nodejs. works great with clustered servers, and child processes that write to shared or static file-stores: scribbles.js
    // scribbles.js a nonblocking, threadsafe file writer/appender for nodejs
    
    var fs = require('fs'),
    	pth = require('path'),
    	cueMngr = {};
    
    function Scribbles(fileNm) {
    	this.handle = fileNm;
    	this.canWrite = false;
    	this.actionsRoster = [];
    };
    
    var scribbles = Scribbles.prototype;
    
    scribbles.action = function (err, dta, actionCue) {
    	if (err) {
    		throw err;
    	}
    	return actionCue();
    }
    
    scribbles.assign = function (func) {
    	this.action = func;
    	return this;
    }
    
    scribbles.scribble = function (dta, func) {
    	if (this.canWrite) {
    		this.actionCue = dta;
    		if (func) {
    			this.actionsRoster.push(func);
    		}
    	} 
    	else {
    		this.canWrite = true;
    		var slf = this,
    			taskProxy = {};
    		fs.appendFile(this.handle, dta, function (err) {
    			function actionCue() {
    				slf.canWrite = false;
    				if (slf.actionCue) {
    					var dta = slf.actionCue;
    					slf.scribble(dta);
    					slf.actionCue = null;
    				}
    			}
    			slf.action(err, dta, actionCue);
    			while (taskProxy = slf.actionsRoster.shift()) {
    				return taskProxy(err);
    			}
    			if (func) {
    				return func(err);
    			}
    		});
    	}
    	return this;
    };
    
    module.exports = function (fil) {
    	var nm = pth.resolve(fil);
    	return (cueMngr[nm] = cueMngr[nm] || new Scribbles(fil));
    }
    
    

    public by HeathDernovich modified Aug 25, 2014  236527  0  4  1

    Fastest way to add new nodes to the DOM

    Fastest way to add new nodes to the DOM: frag.js
    var frag = document.createDocumentFragment();
    
    ajaxResult.items.forEach(function(item) {
        // Create the LI element
        var li = document.createElement('li');
        li.innerHTML = item.text;
    
        // Do some normal node operations on the LI here,
        // like add classes, modify attributes, 
        // add event listeners, add child nodes, etc.
    
        // *Instead place the LI into the fragment*
        frag.appendChild(li);
    });
    
    // Lastly, mass-inject all list items via the DocumentFragment
    document.querySelector('ul').appendChild(frag);
    
    

    public by merqlove modified Sep 6, 2014  207662  2  4  2

    AngularJS / NodeWebkit logger service.

    AngularJS / NodeWebkit logger service.: logger.coffee
    'use strict';
    
    angular.module('vc.messages')
    .factory "logger", ['$log', 'NwService', ($log, NwService) ->
      log4js = require('log4js')
    
      log4js.configure {
        appenders: [
          {
            type: 'console'
            layout: {
              type: 'pattern'
              pattern: "%m%n"
            }
            category: 'console'
          },
          {
            type: 'file'
            absolute: true
            filename: NwService.dataPath() + '/app.log'
            category: 'file'
            maxLogSize: 1024*1024
            numBackups: 3
            layout: {
              type: 'pattern'
              pattern: "[%d %r] [%p] - %m%n"
            }
          },
        ]
        levels: {
          "[all]": "INFO",
          "console": NwService.isProduction() ? "OFF" : "DEBUG",
          "file": "ERROR"
        }
      }
    
      consoleLogger = log4js.getLogger('console')
    
      ['Trace','Debug','Info','Warn','Error','Fatal'].forEach (levelString) ->
        level = log4js.levels.toLevel(levelString)
    
        consoleLogger[levelString.toLowerCase()] = () ->
          return false unless consoleLogger.isLevelEnabled(level)
          args = Array.prototype.slice.call(arguments)
          switch levelString
            when 'Info', 'Warn'
              $log[levelString.toLowerCase()](args)
            else
              args.unshift(level)
              consoleLogger.log.apply(consoleLogger, args)
    
      return {
        file: log4js.getLogger('file')
        console: consoleLogger
      }
    ]
    
    

    public by sTiLL-iLL modified Sep 4, 2014  195319  6  9  23

    Watchable.js ie. observable & chainable

    eventing wrapper for objects and nodes
    
    // uses browser(ed) version of event-emitter as a dependancy
    
    var events = EventEmitter;
     
    function watchable(obj) {
    	
    	var that = this;
    	var first = true;
    	var x = null;
    	var ob = obj || undefined;
    
    	if(first) { 	
    		events.call(this);
    		x = obj || null;
    		first = false;
    		return this;
    	 } 
    	 else {
    		if(!ob) {
    			return x;
    		} 
    		else {
    			x = ob;
    			ob = undefined;
    			this.emit("change", x);
    		}
             	 }
    };
    
    watchable.prototype = Object.create(events.prototype, {
        			constructor: {
          				value: watchable
       			}
      		});
    
    watchable.prototype.val = function(v) {
    			if(!v) { 
    				return x;
    			}
    			x = v;
      			this.emit('change', x);
    			return this;
      		};
    
    watchable.prototype.fire = function(str, obj) {
      			this.emit(str, obj);
    			return this;
      		};
    
    watchable.prototype.when = function(str, fnc) {
      			this.on(str, function(ev) {
    					fnc(ev);
    				});
    			return this;
      		};
    
    watchable.prototype.change = function() {
      			this.emit('change', x);
    			return this;
      		};
    

    public by cghersi modified Jun 2, 2014  185023  1  6  1

    Use the Raw HTML content in XSLT transformations

    Usage of copy-of element allows to get the exact content of an XML node and put it as raw HTML, so that e.g. are not stripped out as instead happens with
    <myXmlNode>
    	<question>
    	Some text <br/> separated < br/> by new lines
    	</question>
    </myXmlNode>
    
    <span>
    	<xsl:copy-of select="question"/>
    </span>

    public by Tech_JA modified Oct 26, 2017  67  0  3  0

    Get the current date and time

    Get the current date and time
    var datetime = "";
    
    function getdate() {
        var currentdate = new Date();
        datetime = currentdate.getFullYear();
        datetime += "/";
        if (currentdate.getMonth() < 10) {
            datetime += "0" + currentdate.getMonth();
        } else {
            datetime = currentdate.getMonth();
        }
        datetime += "/";
        if (currentdate.getDate() < 10) {
            datetime += "0" + currentdate.getDate();
        } else {
            datetime += currentdate.getDate();
        }
        datetime += " ";
        if (currentdate.getHours() < 10) {
            datetime += " " + currentdate.getHours();
        } else {
            datetime += currentdate.getHours();
        }
        datetime += ":";
        if (currentdate.getMinutes() < 10) {
            datetime += "0" + currentdate.getMinutes();
        } else {
            datetime += currentdate.getMinutes();
        }
        datetime += ":";
        if (currentdate.getSeconds() < 10) {
            datetime += "0" + currentdate.getSeconds();
        } else {
            datetime += currentdate.getSeconds();
        }
    }
    
    getdate();
    console.log("data e hora actuais: " + datetime);						

    public by Tech_JA modified Oct 26, 2017  56  0  3  0

    sqlite-sync.js

    
    var sqlite = require('sqlite-sync'); //requiring 
     
    //Connecting - if the file does not exist it will be created 
    sqlite.connect('test/test.db'); 
     
    //Creating table - you can run any command 
    sqlite.run("CREATE TABLE COMPANYS(ID  INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL);");
     
    //Inserting - this function can be sync to, look the wiki 
    sqlite.insert("COMPANYS",{NAME:"My COMPANY"}, function(inserid){
    	console.log(inserid);
    });
     
    //Updating - returns the number of rows modified - can be async too 
    var rows_modified = sqlite.update("COMPANYS",{NAME:"TESTING UPDATE"},{ID:1});
     
    //Create your function 
    function test(a,b){
    	return a+b;
    }
     
    //Add your function to connection 
    sqlite.create_function(test);
     
    // Use your function in the SQL 
    console.log(sqlite.run("SELECT ID, test(NAME, ' Inc') as NAME FROM COMPANYS"));
     
    // Closing connection  
    sqlite.close();
    
    					

    public by micurs modified Feb 12, 2014  20821  93  9  4

    Using moment.js in node.js with Typescript

    You can easily install the moment.js library in node by using the command (on Mac): npm install moment After that you need to download its type definition from Git/DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped/tree/master/moment To make it work, however you need to add the following to the moment.d.ts :
    // add this at the end of moment.d.ts to export the moment symbol
    declare module "moment" { export = moment; } 
    
    // After that in your Typescript file you can use import
    import moment = require("moment");
    
       
    • Public Snippets
    • Channels Snippets