Exemple #1
0
 }).parse(data, function (err, tree) {
         if (err) {
             less.writeError(err, options);
         } else {
             try {
                 var css = tree.toCSS({ compress: options.compress });
                 if (output) {
                     var fd = fs.openSync(output, "w");
                     fs.writeSync(fd, css, 0, "utf8");
                 } else {
                     console.log('WARNING: output is undefined');
                     util.print(css);
                 }
             } catch (e) {
                 less.writeError(e, options);
             }
         }
     });
Exemple #2
0
 fs.readFile(path.join('test/less/', name) + '.txt', 'utf8', function (e, expectedErr) {
     sys.print("- " + name + ": ");
     expectedErr = doReplacements(expectedErr, 'test/less/errors/');
     if (!err) {
         if (compiledLess) {
             fail("No Error", 'red');
         } else {
             fail("No Error, No Output");
         }
     } else {
         var errMessage = less.formatError(err);
         if (errMessage === expectedErr) {
             ok('OK');
         } else {
             difference("FAIL", expectedErr, errMessage);
         }
     }
 });
Exemple #3
0
	function updateSpeed() {
		// once per second
		let now = (new Date()).getTime();
		let lastMeter = lastMeterTimes[lastMeterTimes.length - 1];

		if (now - lastMeter >= 1500) {
			currentSpeed = 0;
		} else {
			currentSpeed = parseInt((1 / (lastMeter - lastMeterTimes[lastMeterTimes.length - 2])) * 100000, 10) / 100;
		}

		util.print("\u001b[2J\u001b[0;0H");
		console.log("lastMeter: " + lastMeter);
		console.log("currentSpeed: " + currentSpeed);
		console.log("meters: " + meters);
		meters = 0;
		lastChecked = now;
	}
 child.on('message', function(msg) {
     if (msg.event === 'assertionDone') {
         log.assertion(msg.data);
     } else if (msg.event === 'testDone') {
         log.test(msg.data);
     } else if (msg.event === 'done') {
         msg.data.code = opts.code.path;
         log.summary(msg.data);
         if (opts.log.testing) {
             util.print('done');
         }
         callback(null, msg.data);
         kill();
     } else if (msg.event === 'uncaughtException') {
         callback(_.extend(new Error, msg.data));
         kill();
     }
 });
Exemple #5
0
function usage() {
  sys.print([
    'usage: nodemon [options] [script.js] [args]',
    'e.g.: nodemon script.js localhost 8080',
    '',
    'Options:',
    '  --js               monitor only JavaScript file changes',
    '                     (default if ignore file not found)',
    '  -d n, --delay n    throttle restart for "n" seconds',
    '  --debug            enable node\'s native debug port',
    '  -v, --version      current nodemon version',
    '  -h, --help         this usage',
    '',
    'Note: if the script is omitted, nodemon will try "main" from package.json',
    '',
    'For more details see http://github.com/remy/nodemon/\n'
  ].join('\n'));
}
Exemple #6
0
function help(){
  sys.print([
    'USAGE: jasmine-node [--color|--noColor] [--verbose] [--coffee] directory'
  , ''
  , 'Options:'
  , '  --color            - use color coding for output'
  , '  --noColor          - do not use color coding for output'
  , '  -m, --match REGEXP - load only specs containing "REGEXPspec"'
  , '  -i, --include DIR  - add given directory to node include paths'
  , '  --verbose          - print extra information per each test run'
  , '  --coffee           - load coffee-script which allows execution .coffee files'
  , '  --junitreport      - export tests results as junitreport xml format'
  , '  --teamcity         - converts all console output to teamcity custom test runner commands. (Normally auto detected.)'
  , ''
  ].join("\n"));

  process.exit(-1);
}
Exemple #7
0
 child.on('message', function(msg) {
     if (msg.event === 'assertionDone') {
         log.assertion(msg.data);
     } else if (msg.event === 'testDone') {
         log.test(msg.data);
     } else if (msg.event === 'done') {
         msg.data.code = opts.code.path;
         
         // DH: print test-name instead of code-name
         //msg.data.code = opts.tests[0].path;
         
         log.summary(msg.data);
         if (opts.log.testing) {
             util.print('done');
         }
         callback(msg.data);
         child.kill();
     }
 });
Exemple #8
0
	stdin.on('data', function (line) {
		str = line.toString();
		if(str.length >= 140){
			str = str.substring(0,140);// truncates to 140 characters
			console.log("[Truncated] "+str);
		}
		// send req to twitter
		if(str.trim()!==""){
			twit.verifyCredentials(function (err, data) {
				if(err){console.log(err);}
			}).updateStatus(str,
				function (err, data) {
				if(err){console.log(err);}
				else{console.log("[✓] " + str);}
				}
			);
		}
	util.print('> ');
	});
Exemple #9
0
var startSSL = function() {

    var privateKey="";
    var certificate="";
    try {
        privateKey = fs.readFileSync('certs/server.key').toString();
        certificate = fs.readFileSync('certs/server.cert').toString();
    } catch ( e ) {
        util.print( "no certificate found. generating self signed cert.\n" );
    }
    
    if ( privateKey !== "" && certificate !== "" ) {
        https.createServer({ key: privateKey, cert: certificate }, sslapp).listen( config.listenPort, config.listenIP );
    } else {
        var spawn = require('child_process').spawn;
        
        var genSelfSignedCert = function() {
            var genkey = spawn( 'openssl', [
                'req', '-x509', '-nodes',
                '-days', '365',
                '-newkey', 'rsa:2048',
                '-keyout', 'certs/server.key',
                '-out', 'certs/server.cert',
                '-subj',
                '/C=' + config.country + '/ST=' + config.state + "/L=" + config.locale + "/CN=" + config.commonName + "/subjectAltName=" + config.subjectAltName
            ]);
            genkey.stdout.on('data', function(d) { util.print(d) } );
            genkey.stderr.on('data', function(d) { util.print(d) } );
            genkey.addListener( 'exit', function( code, signal ) {
                fs.chmodSync('certs/server.key', '600');
                loadServer();
            });
        };        
        var loadServer = function() {
            privateKey = fs.readFileSync('certs/server.key').toString();
            certificate = fs.readFileSync('certs/server.cert').toString();
            https.createServer({ key: privateKey, cert: certificate }, sslapp).listen( config.listenPort, config.listenIP );
        };

        genSelfSignedCert();
    }
};
Exemple #10
0
NodeMenu.prototype._printMenu = function() {
    var self = this;

    util.print(self.CLEAR_CODE);
    var self = this;
    self._printHeader();    
    for (var i = 0; i < self.menuItems.length; ++i) {
        var menuItem = self.menuItems[i];
        printableMenu = menuItem.getPrintableString();
        if (menuItem.menuType === MenuType.ACTION) {
            self.consoleOutput(menuItem.number + ". " + printableMenu);
        } else if (menuItem.menuType === MenuType.DELIMITER) {
            self.consoleOutput(printableMenu);
        }
    }

    self.consoleOutput('\nPlease provide input at prompt as: >> ItemNumber arg1 arg2 ... (i.e. >> 2 "string with spaces" 2 4 noSpacesString true)');

    process.stdout.write("\n>> ");
};
Exemple #11
0
    function(destinationCol, mergedTranslations, done) {
        var successfullyUpdatedTranslations = [];

        util.print('Merging translations...');
        async.eachSeries(mergedTranslations, function(mergedTranslation, done) {
            destinationCol.update({
                _id: mergedTranslation._id
            }, {$set: _.pick(mergedTranslation, argv.p)}, function(err, numberOfUpdatedDocuments) {
                if(numberOfUpdatedDocuments) {
                    successfullyUpdatedTranslations.push(mergedTranslation);
                }
                done(err, numberOfUpdatedDocuments);
            });
        }, function(err, result) {
            if(!err) {
                util.print(util.format(' [Merged %d translations]\n', successfullyUpdatedTranslations.length));
            }
            done(err, result);
        });
    }
Exemple #12
0
var createHelperFile = function() {
    if (null === maxPathLength) longestPath()
    var printable  = 'Helper file: '
    var padding    = ''
    if (printable.length !== maxPathLength)
        padding = new Array(maxPathLength - printable.length + 3).join(' ')
    util.print((printable + padding).blue)
    if (true == fs.existsSync(helperFile)) {
        console.log('Helper already exists'.yellow)
    } else {
        try {
            fs.createReadStream(templateFolder + '/helper.js')
                .pipe(fs.createWriteStream(helperFile))
            fs.createReadStream(templateFolder + '/.gitkeep')
                .pipe(fs.createWriteStream(process.cwd() + '/test/screenshots/.gitkeep'))
            console.log('Successfully created'.green)
        } catch (e) {
            console.log(('ERROR could not create - ' + e.message).red)
        }
    }
}
Exemple #13
0
    exec(cmd, function (error, stdout, stderr) {
        if (error) {
            console.log("HHVM error: " + error);
            return;
        } 
        
        util.print('Compiling with HHVM: ' + stdout);
        
        var outputFileName = hhvmDir + "/hhbc.json";
        var cmd = "../bin/run_json_export " + hhvmDir + "/hhvm.hhbc " + outputFileName;
        exec(cmd, function (error, stdout, stderr) {
            if (error) {
                console.log("Error: " + error);
                return;
            }
            
            util.print('Program text: ' + stdout);
            
            console.log("JSON file written to " + outputFileName);

            fs.readFile(outputFileName, 'utf8', function (error, data) {
                if (error) {
                    console.log(error);
                    return;
                }
                
                // Delete temp files
                var rm = require('rimraf');
                function rmError(error) {
                    if (error) {
                        console.log(error);
                    }
                }
                rm(scriptFileName, rmError);
                rm(hhvmDir, rmError);
                
                onCompiled(data);
            });
        });
    });
Exemple #14
0
(function() {
  var assert = require('assert'),
      child = require('child_process'),
      util = require('util'),
      common = require('../common');
  if (process.env['TEST_INIT']) {
    util.print('Loaded successfully!');
  } else {
    // change CWD as we do this test so its not dependant on current CWD
    // being in the test folder
    process.chdir(__dirname);

    child.exec(process.execPath + ' test-init', {env: {'TEST_INIT': 1}},
        function(err, stdout, stderr) {
          assert.equal(stdout, 'Loaded successfully!', '`node test-init` failed!');
        });
    child.exec(process.execPath + ' test-init.js', {env: {'TEST_INIT': 1}},
        function(err, stdout, stderr) {
          assert.equal(stdout, 'Loaded successfully!', '`node test-init.js` failed!');
        });

    // test-init-index is in fixtures dir as requested by ry, so go there
    process.chdir(common.fixturesDir);

    child.exec(process.execPath + ' test-init-index', {env: {'TEST_INIT': 1}},
        function(err, stdout, stderr) {
          assert.equal(stdout, 'Loaded successfully!', '`node test-init-index failed!');
        });

    // ensures that `node fs` does not mistakenly load the native 'fs' module
    // instead of the desired file and that the fs module loads as expected in node
    process.chdir(common.fixturesDir + '/test-init-native/');

    child.exec(process.execPath + ' fs', {env: {'TEST_INIT': 1}},
        function(err, stdout, stderr) {
          assert.equal(stdout, 'fs loaded successfully', '`node fs` failed!');
        });
  }
})();
/**
 * Run one spawned instance with tests
 * @param {Object} opts
 * @param {Function} callback
 */
function runOne(opts, callback) {
    var child;

    child = cp.fork(
        __dirname + '/child.js',
        [JSON.stringify(opts)],
        {env: process.env}
    );

    function kill() {
        process.removeListener('exit', kill);
        child.kill();
    }

    child.on('message', function(msg) {
        if (msg.event === 'assertionDone') {
            log.assertion(msg.data);
        } else if (msg.event === 'testDone') {
            log.test(msg.data);
        } else if (msg.event === 'done') {
            msg.data.code = opts.code.path;
            log.summary(msg.data);
            if (opts.log.testing) {
                util.print('done');
            }
            callback(null, msg.data);
            kill();
        } else if (msg.event === 'uncaughtException') {
            callback(_.extend(new Error, msg.data));
            kill();
        }
    });

    process.on('exit', kill);

    if (opts.log.testing) {
        util.print('\nTesting ', opts.code.path + ' ... ');
    }
}
 }).parse(data, function (err, tree) {
     if (err) {
         less.writeError(err, options);
         process.exit(1);
     } else {
         try {
             css = tree.toCSS({
                 compress: options.compress,
                 yuicompress: options.yuicompress
             });
             if (output) {
                 fd = fs.openSync(output, "w");
                 fs.writeSync(fd, css, 0, "utf8");
             } else {
                 sys.print(css);
             }
         } catch (e) {
             less.writeError(e, options);
             process.exit(2);
         }
     }
 });
Exemple #17
0
function endTest() {
    var leaked = checkGlobalLeaks();
    if (failedTests + passedTests === totalTests) {
        sys.puts("");
        sys.puts("");
        if (failedTests > 0) {
            sys.print(failedTests);
            sys.print(stylize(" Failed", "red"));
            sys.print(", " + passedTests + " passed");
        } else {
            sys.print(stylize("All Passed ", "green"));
            sys.print(passedTests + " run");
        }
        if (leaked.length > 0) {
            sys.puts("");
            sys.puts("");
            sys.print(stylize("Global leak detected: ", "red") + leaked.join(', '));
            sys.print("\n");
        }
    }
}
Exemple #18
0
 function main (args) {
     console.log('args: ' + args);
     
     if (args && args instanceof Array){
         while (args.length > 0) {
             var v = args.shift();
             switch(v) {
                 case '-v':
                 case '--version':
                     util.print('version ' + VERSION);
                     process.exit(0);
                 default:
                     break;
             }
         }
     }
     
     var files = getAllDistFiles(curPath);
     files.forEach(function (file) {
         var dir = getDir(file);
         runCmds(['spm build -compiler=clouser'], dir);
     })
 }
var next = function() {
    if (apps.length) {
        var len = apps.length;
        var doc = apps.pop();
        util.print(verb + ' (' + len + '): [' + (doc.username + '/' + doc.repo_id + '/' + doc.start + ':' + doc.port).blue + ']');
        var method = 'app_' + action;
        app[method]({
            query: {
                repo_id: doc.repo_id,
                restart_key: config.opt.restart_key
            }
        }, {
            send: function(data) {
                if (data instanceof Object) {
                    if (data.status.indexOf('failed') > -1) {
                        f++;
                    } else {
                        g++;
                    }
                    util.print(' [' + ((data.status.indexOf('failed') > -1) ? bad.red.bold : good.bold.green) + ']\n');
                } else {
                    g++;
                    util.print(' [' + '!!'.yellow.bold + ']\n');
                }
                //Let the process fire up and daemonize before starting the next one
                setTimeout(next, 500);
            }
        });
        
    } else {
        util.log(('All ' + count + ' apps ' + past).bold);
        util.log(g + ' apps ' + past + ' successfully');
        if (f) {
            util.log((f + ' apps failed to ' + action).red.bold);
        }
    }
}
Exemple #20
0
function help() {
  util.print([
    '',
    ' Usage: nodemon [options] [script.js] [args]',
    '',
    ' Options:',
    '',
    '  -d, --delay n      throttle restart for "n" seconds',
    '  -w, --watch dir    watch directory "dir". use once for each',
    '                     directory to watch',
    '  -x, --exec app     execute script with "app", ie. -x "python -v"',
    '  -I, --no-stdin     don\'t try to read from stdin',
    '  -q, --quiet        minimise nodemon messages to start/stop only',
    '  --exitcrash        exit on crash, allows use of nodemon with',
    '                     daemon tools like forever.js',
    '  -L, --legacy-watch Forces node to use the most compatible',
    '                     version for watching file changes',
    '  -v, --version      current nodemon version',
    '  -e, --ext          extensions to look for Example: ".js|.html|.css"',
    '  -h, --help         you\'re looking at it',
    '',
    ' Note: if the script is omitted, nodemon will try to ',
    ' read "main" from package.json and without a .nodemonignore,',
    ' nodemon will monitor .js and .coffee by default.',
    '',
    ' Examples:',
    '',
    '  $ nodemon server.js',
    '  $ nodemon -w ../foo server.js apparg1 apparg2',
    '  $ PORT=8000 nodemon --debug-brk server.js',
    '  $ nodemon --exec python app.py',
    '',
    ' For more details see http://github.com/remy/nodemon/',
    ''
  ].join('\n') + '\n');
  process.exit(0);
}
Exemple #21
0
/**
 * Run one spawned instance with tests
 * @param {Object} opts
 * @param {Function} callback
 */
function runOne(opts, callback) {
    var child;

    child = cp.fork(
        __dirname + '/child.js',
        [JSON.stringify(opts)],
        {env: process.env}
    );
    
    child.on('message', function(msg) {
        if (msg.event === 'assertionDone') {
            log.assertion(msg.data);
        } else if (msg.event === 'testDone') {
            log.test(msg.data);
        } else if (msg.event === 'done') {
            msg.data.code = opts.code.path;
            
            // DH: print test-name instead of code-name
            //msg.data.code = opts.tests[0].path;
            
            log.summary(msg.data);
            if (opts.log.testing) {
                util.print('done');
            }
            callback(msg.data);
            child.kill();
        }
    });

    process.on('exit', function() {
        child.kill();
    });

    if (opts.log.testing) {
        util.print('\nTesting ', opts.code.path + ' ...\n');
    }
}
 job.fetch(function(err, job) {
     if (err) {
         callback(err);
     }
     else {
         // If the user asked for verbose output,
         // then write out the status of the search
         var properties = job.properties();
         if (isVerbose) {
             var progress    = (properties.doneProgress * 100.0) + "%";
             var scanned     = properties.scanCount;
             var matched     = properties.eventCount;
             var results     = properties.resultCount;
             var stats = "-- " +
                 progress + " done | " +
                 scanned  + " scanned | " +
                 matched  + " matched | " +
                 results  + " results";
             print("\r" + stats + "                                          ");
         }
         
         Async.sleep(1000, iterationDone);
     }
 });
          restartTimer = setTimeout(function () {
            if (program.options.verbose) util.log('[nodemon] restarting due to changes...');
            files.forEach(function (file) {
              if (program.options.verbose) util.log('[nodemon] ' + file);
            });
            if (program.options.verbose) util.print('\n\n');

            if (child !== null) {
              // When using CoffeeScript under Windows, child's process is not node.exe
              // Instead coffee.cmd is launched, which launches cmd.exe, which starts node.exe as a child process
              // child.kill() would only kill cmd.exe, not node.exe
              // Therefore we use the Windows taskkill utility to kill the process and all its children (/T for tree)
              if (isWindows) {
                // For the on('exit', ...) handler above the following looks like a crash, so we set the killedAfterChange flag
                killedAfterChange = true;
                // Force kill (/F) the whole child tree (/T) by PID (/PID 123)
                exec('taskkill /pid '+child.pid+' /T /F');
              } else {
                child.kill('SIGUSR2');
              }
            } else {
              startNode();
            }
          }, restartDelay);
Exemple #24
0
this.report = function (data) {
    var event = data[1];

    switch (data[0]) {
        case 'subject':
            puts('\n♢ ' + stylize(event, 'bold') + '\n');
            break;
        case 'context':
            puts(console.contextText(event));
            break;
        case 'vow':
            puts(console.vowText(event));
            break;
        case 'end':
            util.print('\n');
            break;
        case 'finish':
            puts(console.result(event).join('\n'));
            break;
        case 'error':
            puts(console.error(event));
            break;
    }
};
Exemple #25
0
    check : function(_patsy){


      try {

        /**
         * Require config from the library
         *
         * @var     Object
         * @source  patsy
         */
        var config      = require('./config')({
          app_path  : opts.app_path,
          verbose   : opts.verbose
        });

        var _config    = config.load();


        if(typeof _config !== 'undefined'){

          util.print('[Patsy]'.yellow + ': I found a scripture of configuration Sire! It reads: \n');
          util.print('[Patsy]'.yellow + ': "F..fo..\n');
          util.print('[Patsy]'.yellow + ': Foo..foo.foou..\n');
          util.print('[Patsy]'.yellow + ': Follow the path of "' + _config.project.environment.abs_path + '" to complete the quest of.. \n');
          util.print('[Patsy]'.yellow + ': Of.. ehm, of ' + _config.project.details.name + '"! \n' );
          util.print('[King Arthur]'.magenta + ': Well? Don\'t just stand there, saddle up! And summon the other squires!\n');

          _patsy.load(_config);

          //return true;
        } else {

          config.ask(_patsy);

        }

      } catch (err) {
        console.log('project.check', err);
        //return false;
      }
    }
/**@function    displayTime
  *@description takes an array of TimeObjects as a parameter, and prints their
  *             ID field and either totalTime or workTime, depending on the value 
  *             of another parameter called flag. Uses the type parameter to identify 
  *             to the user what kind of array has been passed/is being printed.  
  *             
  *@param array: an array of type TimeObject to be printed to the screen. 
  *@param flag:  a string indicating which field of the TimeObject items
  *              should be printed (either 'total', for totalTime, or 'work', for workTime)
  */
function displayTime(array,flag,type){
    if(flag=="total"){
	util.print("\n                               Time devoted to each ",type," (total):\n");
	util.print("||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||\n");
	var totalTime;
        for(var i=0; i<array.length; i++){
	    totalTime = convertToString(array[i].totalTime);
	    if(totalTime != "")
		util.print("Total time for ",type," \"",array[i].id,"\": " + totalTime + "\n");
	}
    }
    else if(flag=="work"){
	util.print("\n\n                          Time devoted to each ",type," (Business Hours):\n");
	util.print("||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||\n");
	var workTime;
        for(var i=0; i<array.length; i++){
	    workTime = convertToString(array[i].workTime);
	    if(workTime != "")
		util.print("Time during work hours for ",type," \"",array[i].id,"\": " + workTime + "\n");
	}
    }
}
 child.stdout.on('data', function (data) {
   util.print(data);
 });
Exemple #28
0
 msg.methods.forEach(function(v, k) {
   util.print(k+1 +": " + v[0] + " - " + v[1] + "\n");
 });
Exemple #29
0
function testPrint() {
  // only assures we don't fail - doesn't test the actual result
  util.print('message to stdout', 'and', {})
  vassert.testComplete();
}
Exemple #30
0
function output_json(object) {
  // util.print(JSON.stringify(object));
  util.print(JSON.stringify(object, null, 2)+'\n');
}