Example #1
0
function child() {
  var util = require('util');
  var debug = util.debuglog('tud');
  debug('this', { is: 'a' }, /debugging/);
  debug('number=%d string=%s obj=%j', 1234, 'asdf', { foo: 'bar' });
  console.log('ok');
}
Example #2
0
function child(section) {
  const util = require('util');
  const debug = util.debuglog(section);
  debug('this', { is: 'a' }, /debugging/);
  debug('num=%d str=%s obj=%j', 1, 'a', { foo: 'bar' });
  console.log('ok');
}
Example #3
0
  constructor() {
    super({
      objectMode: true
    });

    this._log = debuglog('http');

    this._connection = null;
    this._writer = null;
    this._encoder = null;
    this._request = null;

    this._host = null;
    this._port = null;
    this._method = 'GET';
    this._path = '/';
    this._query = {};
    this._headers = {};

    this._handleError = (e) => this._error(e);
    this._handleFinish = () => this._finish();
    this._handleResponse = (r) => this._response(r);

    this._bindThis();
  }
Example #4
0
  constructor() {
    super({
      objectMode: true
    });

    this._log = debuglog('ws');

    this._connection = null;
    this._response = null;
    this._writer = null;
    this._encoder = null;

    this._method = 'GET';
    this._path = '/';
    this._query = {};
    this._headers = {};

    this._ended = false;

    this._handleData = (d) => this._data(d);
    this._handleFinish = () => this._finish();

    this._bindThis();
  }
Example #5
0
'use strict';

module.exports = Readable;
Readable.ReadableState = ReadableState;

const EE = require('events');
const Stream = require('stream');
const { Buffer } = require('buffer');
const util = require('util');
const debug = util.debuglog('stream');
const BufferList = require('internal/streams/BufferList');
const destroyImpl = require('internal/streams/destroy');
const errors = require('internal/errors');
var StringDecoder;

util.inherits(Readable, Stream);

const kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];

function prependListener(emitter, event, fn) {
  // Sadly this is not cacheable as some libraries bundle their own
  // event emitter implementation with them.
  if (typeof emitter.prependListener === 'function')
    return emitter.prependListener(event, fn);

  // This is a hack to make sure that our error handler is attached before any
  // userland ones.  NEVER DO THIS. This is here only because this code needs
  // to continue to work with older versions of Node.js that do not include
  // the prependListener() method. The goal is to eventually remove this hack.
  if (!emitter._events || !emitter._events[event])
Example #6
0
'use strict'

const util = require('util')
const co = require('co')
const Busboy = require('busboy')
const { send, createError } = require('micro')
const meter = require('stream-meter')

const debuglog = util.debuglog('asset_api')

module.exports = createAssetAPI

function createAssetAPI ({ s3 }) {
  const driver = process.env.NODE_ENV === 'production'
    ? createAWSDriver({ s3 })
    : createFSDriver({ uploadDir: 'assets' })
  debuglog(
    'using',
    process.env.NODE_ENV === 'production'
      ? 'aws driver'
      : 'fs driver'
  )
  return co.wrap(function * assetAPI (req, res) {
    if (!req.headers['x-website']) throw createError(400)
    if (req.headers['x-website-isnew']) throw createError(404)
    if (req.method === 'POST') {
      const { Bytes: bytes } = yield uploadFile(req, driver)
      send(res, 200, { bytes })
      return null
    } else {
      throw createError(405)
Example #7
0
'use strict';

const internalModule = require('internal/module');
const internalUtil = require('internal/util');
const util = require('util');
const inherits = util.inherits;
const Stream = require('stream');
const vm = require('vm');
const path = require('path');
const fs = require('fs');
const Interface = require('readline').Interface;
const Console = require('console').Console;
const Module = require('module');
const domain = require('domain');
const debug = util.debuglog('repl');

const parentModule = module;
const replMap = new WeakMap();

try {
  // hack for require.resolve("./relative") to work properly.
  module.filename = path.resolve('repl');
} catch (e) {
  // path.resolve('repl') fails when the current working directory has been
  // deleted.  Fall back to the directory name of the (absolute) executable
  // path.  It's not really correct but what are the alternatives?
  const dirname = path.dirname(process.execPath);
  module.filename = path.resolve(dirname, 'repl');
}
Example #8
0
'use strict'

// parse - parse xml and test events

module.exports = parse

const pickup = require('../../')
const { debuglog } = require('util')

const debug = debuglog('pickup')

function defaults (opts) {
  if (opts.eventMode === undefined) {
    opts.eventMode = true
  }
  if (opts.charset === undefined) {
    opts.charset = Math.round(Math.random()) > 0.5 ? 'utf8' : null
  }
  return opts
}

function parse (opts, cb) {
  opts = defaults(opts)

  const xml = opts.xml
  const wanted = opts.wanted
  const t = opts.t
  const parser = pickup(opts)

  let e = 0
/*</replacement>*/

var Stream = require('stream');

/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/

var StringDecoder;


/*<replacement>*/
var debug = require('util');
if (debug && debug.debuglog) {
    debug = debug.debuglog('stream');
} else {
    debug = function () {
    };
}
/*</replacement>*/


util.inherits(Readable, Stream);

function ReadableState(options, stream) {
    var Duplex = require('./_stream_duplex');

    options = options || {};

    // the point at which it stops calling _read() to fill the buffer
Example #10
0
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

var Timer = process.binding('timer_wrap').Timer;
var L = require('_linklist');
var assert = require('assert').ok;

var kOnTimeout = Timer.kOnTimeout | 0;

// Timeout values > TIMEOUT_MAX are set to 1.
var TIMEOUT_MAX = 2147483647; // 2^31-1

var util = require('util');
var debug = util.debuglog('timer');


// IDLE TIMEOUTS
//
// Because often many sockets will have the same idle timeout we will not
// use one timeout watcher per item. It is too much overhead.  Instead
// we'll use a single watcher for all sockets with the same timeout value
// and a linked list. This technique is described in the libev manual:
// http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#Be_smart_about_timeouts

// Object containing all lists, timers
// key = time in milliseconds
// value = list
var lists = {};
Example #11
0
  this.filename = null;
  this.loaded = false;
  this.children = [];
}
module.exports = Module;

Module._cache = {};
Module._pathCache = {};
Module._extensions = {};
var modulePaths = [];
Module.globalPaths = [];

Module.wrapper = NativeModule.wrapper;
Module.wrap = NativeModule.wrap;
Module._debug = util.debuglog('module');

// We use this alias for the preprocessor that filters it out
const debug = Module._debug;


// given a module name, and a list of paths to test, returns the first
// matching file in the following precedence.
//
// require("a.<ext>")
//   -> a.<ext>
//
// require("a")
//   -> a
//   -> a.<ext>
//   -> a/index.<ext>
Example #12
0
var Promise = require("bluebird");
var _ = require("lodash");
var EventEmitter = require("events");
var util = require("util");
var MemoryStorage = require("./storage/memory");
var RedisStorage = require("./storage/redis");
var debug = util.debuglog("templock");

function categoryCountKey(itemId, category) {
  return "count:" + itemId + ":" + category;
}
function itemCountersKey(itemId) {
  return "counter:" + itemId;
}

function itemLockKey(itemId, category) {
  return "lock:" + itemId + ":" + category;
}

function TempLock(config) {
  EventEmitter.call(this);

  config = config || {};
  config = _.clone(config);
  _.defaults(config, {
    storeTimeout: 3600,
    strategies: [
      {
        category: "main",
        attempts: 10,
        lockFor: 60
Example #13
0
exports.SLAB_BUFFER_SIZE = 10 * 1024 * 1024;

exports.getCiphers = function() {
  var names = process.binding('crypto').getSSLCiphers();
  // Drop all-caps names in favor of their lowercase aliases,
  var ctx = {};
  names.forEach(function(name) {
    if (/^[0-9A-Z\-]+$/.test(name)) name = name.toLowerCase();
    ctx[name] = true;
  });
  return Object.getOwnPropertyNames(ctx).sort();
};


var debug = util.debuglog('tls');

var Connection = null;
try {
  Connection = process.binding('crypto').Connection;
} catch (e) {
  throw new Error('node.js not compiled with openssl crypto support.');
}

// Convert protocols array into valid OpenSSL protocols list
// ("\x06spdy/2\x08http/1.1\x08http/1.0")
function convertNPNProtocols(NPNProtocols, out) {
  // If NPNProtocols is Array - translate it into buffer
  if (Array.isArray(NPNProtocols)) {
    var buff = new Buffer(NPNProtocols.reduce(function(p, c) {
      return p + 1 + Buffer.byteLength(c);
Example #14
0
/*
 * This script starts accounts an associates them with extension connections
 * to pipe events multiplexed by extension
 * to different eventemitters in each account.
 */
require('error-tojson'); // i know, it's evil, but … meh
var isArray = Array.isArray;
var __slice = Array.prototype.slice;
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var xmpp = new (require('lightstream/backend/node-xmpp'));
var JID = xmpp.JID;
var Element = xmpp.Element;
var Connection = require('../../lib/connection');
var Account = require('./account');
var debug = util.debuglog('app:pool:client');


module.exports = Client;
util.inherits(Client, Connection);
function Client(port, accounts, frontend) {
    debug('new client');
    Connection.call(this).bind(port, function () {
        this.emit('unbind');
        this.removeAllListeners();
    });
    this.frontend = frontend;
    this.accounts = accounts;
    this.connections = {};
    this.setupListeners();
}
Example #15
0
'use strict';

const assert = require('assert');
const crypto = require('crypto');
const net = require('net');
const tls = require('tls');
const util = require('util');
const listenerCount = require('events').listenerCount;
const common = require('_tls_common');
const StreamWrap = require('_stream_wrap').StreamWrap;
const Duplex = require('stream').Duplex;
const debug = util.debuglog('tls');
const Timer = process.binding('timer_wrap').Timer;
const tls_wrap = process.binding('tls_wrap');
const TCP = process.binding('tcp_wrap').TCP;
const Pipe = process.binding('pipe_wrap').Pipe;

function onhandshakestart() {
  debug('onhandshakestart');

  var self = this;
  var ssl = self._handle;
  var now = Timer.now();

  assert(now >= ssl.lastHandshakeTime);

  if ((now - ssl.lastHandshakeTime) >= tls.CLIENT_RENEG_WINDOW * 1000) {
    ssl.handshakes = 0;
  }

  var first = (ssl.lastHandshakeTime === 0);
Example #16
0
const errnoException = util._errnoException;
const exceptionWithHostPort = util._exceptionWithHostPort;
const isLegalPort = internalNet.isLegalPort;
const assertPort = internalNet.assertPort;

function noop() {}

function createHandle(fd) {
  var type = TTYWrap.guessHandleType(fd);
  if (type === 'PIPE') return new Pipe();
  if (type === 'TCP') return new TCP();
  throw new TypeError('Unsupported fd type: ' + type);
}


const debug = util.debuglog('net');

function isPipeName(s) {
  return typeof s === 'string' && toNumber(s) === false;
}

exports.createServer = function(options, connectionListener) {
  return new Server(options, connectionListener);
};


// Target API:
//
// var s = net.connect({port: 80, host: 'google.com'}, function() {
//   ...
// });
Example #17
0
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

'use strict';

const util = require('util');
const {
  deprecate, convertToValidSignal, getSystemErrorName
} = require('internal/util');
const { isArrayBufferView } = require('internal/util/types');
const debug = util.debuglog('child_process');
const { Buffer } = require('buffer');
const { Pipe, constants: PipeConstants } = process.binding('pipe_wrap');
const {
  ERR_INVALID_ARG_VALUE,
  ERR_CHILD_PROCESS_IPC_REQUIRED,
  ERR_CHILD_PROCESS_STDIO_MAXBUFFER,
  ERR_INVALID_ARG_TYPE,
  ERR_INVALID_OPT_VALUE,
  ERR_OUT_OF_RANGE
} = require('internal/errors').codes;
const { validateString } = require('internal/validators');
const child_process = require('internal/child_process');
const {
  _validateStdio,
  setupChannel,
Example #18
0
File: loader.js Project: mitar/node
Module._cache = Object.create(null);
Module._pathCache = Object.create(null);
Module._extensions = Object.create(null);
var modulePaths = [];
Module.globalPaths = [];

Module.wrap = function(script) {
  return Module.wrapper[0] + script + Module.wrapper[1];
};

Module.wrapper = [
  '(function (exports, require, module, __filename, __dirname) { ',
  '\n});'
];

const debug = util.debuglog('module');

Module._debug = util.deprecate(debug, 'Module._debug is deprecated.',
                               'DEP0077');

// Given a module name, and a list of paths to test, returns the first
// matching file in the following precedence.
//
// require("a.<ext>")
//   -> a.<ext>
//
// require("a")
//   -> a
//   -> a.<ext>
//   -> a/index.<ext>
Example #19
0
var util=require("util");

NODE_DEBUG="wsp";

util.debuglog("sdfadsfdas");


// util.format

var test1=util.format("wsp love %s","pxh");
console.log(test1);

// 占位符多余不会被替换
var test2=util.format("wsp  love %s and %s","pxh");

console.log(test2);

var age=util.format("王世平 今年 年龄是 %d",25);

console.log(age);

var student={   
    name:"王世平",
    age:25,
    isMan:true,
    wife:null,
    son:undefined,
    birthDay:new Date("1991-07-11"),
    form:{
        country:"china",
        province:"gansu",
Example #20
0
var assert = require('assert')

// fix up some busted stuff, mostly on windows and old nodes
require('./polyfills.js')

// The EMFILE enqueuing stuff

var util = require('util')

function noop () {}

var debug = noop
var util = require('util')
if (util.debuglog)
  debug = util.debuglog('gfs')
else if (/\bgfs\b/i.test(process.env.NODE_DEBUG || ''))
  debug = function() {
    var m = util.format.apply(util, arguments)
    m = 'GFS: ' + m.split(/\n/).join('\nGFS: ')
    console.error(m)
  }

if (/\bgfs\b/i.test(process.env.NODE_DEBUG || '')) {
  process.on('exit', function() {
    debug('fds', fds)
    debug(queue)
    assert.equal(queue.length, 0)
  })
}
Example #21
0
const Util = require('util')
const puff = require('puff/dynamic')
const Notifier = puff(require('node-notifier'), { bind: 'original' })
const WaniKaniEmitter = require('wanikani-emitter')
const open = require('opn')
const meow = require('meow')
const rc = require('rc')
const pkg = require('../package')
const ServiceManager = require('./service-manager')
const FS = require('node-puff/fs')

const dlog = Util.debuglog('wanikani-notifier').bind(Util)

function humanize(duration) {
  return `${Math.floor(duration / 1000 / 60)} minutes`
}

class WaniKaniNotifier extends WaniKaniEmitter {

  constructor(config) {
    super(config)

    config = Object.assign({
      dashboardOnBothPending: false,
      log: dlog
    }, config)

    const log = this.log = config.log
    this.config = config

    if (!config.key) {
Example #22
0
const Git = require('./git');
const filenamify = require('filenamify-url');
const copy = require('./util').copy;
const getUser = require('./util').getUser;
const fs = require('fs-extra');
const globby = require('globby');
const path = require('path');
const util = require('util');

const log = util.debuglog('gh-pages');

function getCacheDir() {
  return path.relative(process.cwd(), path.resolve(__dirname, '../.cache'));
}

function getRepo(options) {
  if (options.repo) {
    return Promise.resolve(options.repo);
  } else {
    const git = new Git(process.cwd(), options.git);
    return git.getRemoteUrl(options.remote);
  }
}

/**
 * Push a git branch to a remote (pushes gh-pages by default).
 * @param {string} basePath The base path.
 * @param {Object} config Publish options.
 * @param {Function} callback Callback.
 */
exports.publish = function publish(basePath, config, callback) {
Example #23
0
// Inspiration for this code comes from Salvatore Sanfilippo's linenoise.
// https://github.com/antirez/linenoise
// Reference:
// * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
// * http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html

'use strict';

const kHistorySize = 30;
const kMincrlfDelay = 100;
const kMaxcrlfDelay = 2000;

const util = require('util');
const debug = util.debuglog('readline');
const inherits = util.inherits;
const Buffer = require('buffer').Buffer;
const EventEmitter = require('events');
const internalReadline = require('internal/readline');
const emitKeys = internalReadline.emitKeys;
const getStringWidth = internalReadline.getStringWidth;
const isFullWidthCodePoint = internalReadline.isFullWidthCodePoint;
const stripVTControlCharacters = internalReadline.stripVTControlCharacters;


exports.createInterface = function(input, output, completer, terminal) {
  var rl;
  if (arguments.length === 1) {
    rl = new Interface(input);
  } else {
    rl = new Interface(input, output, completer, terminal);
  }
Example #24
0
'use strict';

const TimerWrap = process.binding('timer_wrap').Timer;
const L = require('internal/linkedlist');
const assert = require('assert');
const util = require('util');
const debug = util.debuglog('timer');
const kOnTimeout = TimerWrap.kOnTimeout | 0;

// Timeout values > TIMEOUT_MAX are set to 1.
const TIMEOUT_MAX = 2147483647; // 2^31-1


// HOW and WHY the timers implementation works the way it does.
//
// Timers are crucial to Node.js. Internally, any TCP I/O connection creates a
// timer so that we can time out of connections. Additionally, many user
// user libraries and applications also use timers. As such there may be a
// significantly large amount of timeouts scheduled at any given time.
// Therefore, it is very important that the timers implementation is performant
// and efficient.
//
// Note: It is suggested you first read though the lib/internal/linkedlist.js
// linked list implementation, since timers depend on it extensively. It can be
// somewhat counter-intuitive at first, as it is not actually a class. Instead,
// it is a set of helpers that operate on an existing object.
//
// In order to be as performant as possible, the architecture and data
// structures are designed so that they are optimized to handle the following
// use cases as efficiently as possible:
Example #25
0
var http = require('http');
var fs = require('fs');
var url = require('url');
var util = require('util');
var getopt = require('node-getopt');
var common = require('./common');

var programme_cache = [];
var download_history = [];
var domain = 'radio';
var displayDomain = domain;
var pid = '';
var availableOnly = false;
var upcoming = false;

var debuglog = util.debuglog('bbc');

var add_programme = function(obj) {
	programme_cache.push(obj);
};

//-----------------------------------------------------------------------------

function pad(str, padding, padRight) {
	if (typeof str === 'undefined')
		return padding;
	if (padRight) {
		return (str + padding).substring(0, padding.length);
	} else {
		return (padding + str).slice(-padding.length);
	}
Example #26
0
File: kms.js Project: ddffx/kms-cli
'use strict';

var AWS = require('aws-sdk'),
    chalk = require('chalk'),
    util = require('util'),
    debuglog = util.debuglog('KMSAPI'),
    Q = require('q'),
    _ = require('lodash');


var KMSAPI = function() {
    var config;
    if (!(this instanceof KMSAPI)) {
        return new KMSAPI();
    }
    // console.log(chalk.green('env %j'),process.env);
    AWS.config.update({
        region: process.env.AWS_REGION
    });

    if (process.env.AWS_PROFILE) { // set from file
        var credentials = new AWS.SharedIniFileCredentials({ profile: process.env.AWS_PROFILE });
        AWS.config.credentials = credentials;
    }

    config = {
        region: process.env.AWS_REGION,
        accessKeyId: process.env.AWS_ACCESS_KEY_ID,
        secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
        apiVersion: '2014-11-01'
    };
Example #27
0
}


function assertPort(port) {
    if (typeof port !== 'undefined' && !isLegalPort(port))
        throw new RangeError('"port" argument must be >= 0 and < 65536');
}

function noop() {}

function createHandle(fd) {
    return new TCP();
}


var debug = util.debuglog('net');

function isPipeName(s) {
    return typeof s === 'string' && toNumber(s) === false;
}

exports.createServer = function (options, connectionListener) {
    return new Server(options, connectionListener);
};


// Target API:
//
// var s = net.connect({port: 80, host: 'google.com'}, function() {
//   ...
// });
}
function _isUint8Array(obj) {
  return Object.prototype.toString.call(obj) === '[object Uint8Array]' || Buffer.isBuffer(obj);
}
/*</replacement>*/

/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/

/*<replacement>*/
var debugUtil = require('util');
var debug = void 0;
if (debugUtil && debugUtil.debuglog) {
  debug = debugUtil.debuglog('stream');
} else {
  debug = function () {};
}
/*</replacement>*/

var BufferList = require('./internal/streams/BufferList');
var destroyImpl = require('./internal/streams/destroy');
var StringDecoder;

util.inherits(Readable, Stream);

var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];

function prependListener(emitter, event, fn) {
  // Sadly this is not cacheable as some libraries bundle their own
Example #29
0
'use strict';

const net = require('net');
const util = require('util');
const EventEmitter = require('events');
const debug = util.debuglog('http');

// New Agent code.

// The largest departure from the previous implementation is that
// an Agent instance holds connections for a variable number of host:ports.
// Surprisingly, this is still API compatible as far as third parties are
// concerned. The only code that really notices the difference is the
// request object.

// Another departure is that all code related to HTTP parsing is in
// ClientRequest.onSocket(). The Agent is now *strictly*
// concerned with managing a connection pool.

function Agent(options) {
  if (!(this instanceof Agent))
    return new Agent(options);

  EventEmitter.call(this);

  var self = this;

  self.defaultPort = 80;
  self.protocol = 'http:';

  self.options = util._extend({}, options);
Example #30
0
'use strict';

const Stream = require('through2');
const Debuglog = require('util').debuglog;

const debug = Debuglog('nstring');

const read = function (data, encoding) {
    let size = 0;
    const strings = [];

    if (encoding === 'buffer') {
        encoding = undefined;
    }
    else {
        data = new Buffer(data || '', encoding);
    }

    for(let i = 0; i < data.length; i++) {
        const c = data[i];

        if (c === 58) {
            const offset = i + 1;
            size = parseInt(data.toString(encoding, size, i));
            strings.push(data.slice(offset, offset + size));
            i += size + 1;
            size += offset + 1;
            continue;
        }
    }