Construct a Node Server
516740
def makeService(self, options):
        
        return NodeService(
            port=options['port'],
            host=options['host'],
            broker_host=options['broker_host'],
            broker_port=options['broker_port'],
            debug=options['debug']
        )
290766
function init({ id, node, types }) {
  const newNode = buildNamedExport({ id, types });
  node.body.push(newNode);
}
1041044
function(port, options) {
    var stream = new SimpleStream();
    var prompt = 'node> ';
    var rs = repl.start({ prompt: prompt, input: stream, output: stream});
    var replHttpServer = new ReplHttpServer(prompt, stream, rs, options);
    replHttpServer.start(port);
    return rs;
}
943404
function Server (options) {
  options = utils.clone(options || {});

  var ns = this._ns = utils.createNamespace(options);
  var id = this.id = options.id || utils.uniqueId('server');
  var debug = this._debug = utils.debug('server:' + id);
  var me = this;

  var server = this._server = new net.Server();
  server.on('error', function (err) {
    me._debug('emit error: %s', err);
    me.emit('error', err);
  });
  server.on('close', function () {
    me._debug('emit close');
    me.emit('close');
  });
  server.on('listening', function () {
    me._debug('emit listening');
    me.emit('listening');
  });
  server.on('connection', function (s) {
    me._debug('emit connection [%s] %s:%s', s.remoteFamily, s.remoteAddress, s.remotePort);
    me.emit('connection', s);
    me._handleNewConnection(s);
  });

  this._clients = {};
  this._clientCounter = 0;
  this._keyStatus = new KeyStatus(options);

  debug('created');
}
1191400
def __make_server(self):
        ""
        notice('Making server, getting listening socket', self.color)
        self.mode = 's'
        sock = utils.get_server_sock()
        self.__s = sock
        with self.__client_list_lock:
            self.clients = deque()
        self.threads = deque()
        notice('Making beacon', self.color)
        b = Thread(target=self.__beacon_thread, name='beacon')
        b.start()
        self.threads.append(b)
        l = Thread(target=self.__listen_thread, name='listen')
        notice('Starting listen thread', self.color)
        l.start()
        self.threads.append(l)
846514
def node(self, source, args=(), env={}):
        

        return self._exec(self.node_bin, source, args=args, env=env)
1349144
function createServer() {
  function app(req, res, next) {
    app.handle(req, res, next);
  }
  app.method = '*';
  merge(app, proto);
  merge(app, EventEmitter.prototype);
  app.stack = [];
  app.params = [];
  app._cachedEvents = [] ;
  app.routedMethods = {} ;
  app.locals = Object.create(null);
  for (var i = 0; i < arguments.length; ++i) {
    app.use(arguments[i]);
  }

  //create methods app.invite, app.register, etc..
  methods.forEach((method) => {
    app[method.toLowerCase()] = app.use.bind(app, method.toLowerCase()) ;
  }) ;

  //special handling for cdr events
  app.on = function(event, listener) {
    if (0 === event.indexOf('cdr:')) {
      if (app.client) {
        app.client.on(event, function() {
          var args = Array.prototype.slice.call(arguments) ;
          EventEmitter.prototype.emit.apply(app, [event].concat(args)) ;
        }) ;
      }
      else {
        this._cachedEvents.push(event) ;
      }
    }
    //delegate all others to standard EventEmitter prototype
    return EventEmitter.prototype.addListener.call(app, event, listener) ;
  } ;

  return app;
}
412078
function createServer (options, callback) {
  typeforce({
    keeper: 'Object',
    port: 'Number',
    readonly: '?Boolean'
  }, options)

  var keeper = options.keeper
  var port = options.port
  var app = express()
  if (options.readonly) {
    app.set('readonly', true)
  }

  // var mapping

  app.set('keeper', keeper)
  app.use(function (req, res, next) {
    var requestDomain = domain.create()
    requestDomain.add(req)
    requestDomain.add(res)
    requestDomain.on('error', function (err) {
      debug('Uncaught error, processing in domain error handler: ' + err.message)
      errorHandler(err, req, res)
    })

    res.on('close', requestDomain.dispose.bind(requestDomain))
    requestDomain.run(next)
  })

  app.use(function (req, res, next) {
    if (req.hostname !== 'localhost' && req.hostname !== '127.0.0.1') {
      throw utils.httpError(400, 'Only local requests permitted')
    }

    next()
  })

  /**
   * Routes
   */
  router(app)

  /**
   * Error Handling
   */
  app.use(errorHandler)

  // client.externalIp(function(err, ip) {
  //   console.log('External ip', ip)
  //   keeper.externalIp(ip)
  // })

  // var ttl = 144000

  process.on('exit', cleanup)
  process.on('SIGINT', cleanup)
  process.on('SIGTERM', cleanup)
  process.on('uncaughtException', function (err) {
    console.log('Uncaught exception, caught in process catch-all: ' + err.message)
    console.log(err.stack)
  })

  // if (require.main === global.module) {
  // run directly, not as sub-app

  // var mappingIntervalId = setInterval(createPortMapping, ttl)
  // var pubPort = port
  var privPort = port
  var serverIsUp
  // var portPromise = createPortMapping()
  // portPromise.done(checkReady)

  var server = app.listen(privPort, function () {
    serverIsUp = true
    checkReady()
  })

  function checkReady () {
    if (serverIsUp
      // && portPromise.inspect().state === 'fulfilled'
      && callback) {
      callback(null, server)
    }
  }

  function errorHandler (err, req, res, next) {
    if (res.finished) return

    var code = err.code || 500
    var msg = 'code' in err ? err.message : 'There was an error with your request. Please contact support@tradle.io'

    // log('Error:' + err.message)
    res.status(code).json({
      code: code,
      message: msg
    }, null, 2)
  }

  // function createPortMapping () {
  //   return ports.mapPort({
  //       public: pubPort,
  //       private: privPort,
  //       hijack: true
  //     })
  //     .then(function () {
  //       mapping = {
  //         public: pubPort,
  //         private: privPort
  //       }
  //     })
  //     .catch(function (err) {
  //       console.error('Failed to create port mapping, but continuing', err)
  //       clearInterval(mappingIntervalId)
  //     // process.exit()
  //     })
  // }

  function cleanup () {
    if (!server) return

    debug('CLEANUP')
    if (server) {
      try {
        server.close()
      } catch (err) {}
      server = null
    }

    // if (mapping) {
    //   clearInterval(mappingIntervalId)
    //   ports.unmapPort(mapping['public'])
    //   mapping = null
    // }

    setTimeout(process.exit.bind(process), 1000)
  }

  return server
}
357278
function Server(/* [options], [connectionListener] */) {
    events.EventEmitter.call(this);
    var self = this;

    var options;
    if (typeof arguments[0] === 'function') {
        options = {};
        this.on('connection', arguments[0]);
    } else {
        options = arguments[0] || {};
        if (typeof arguments[1] === 'function') {
            this.on('connection', arguments[1]);
        }
    }

    this._server = net.createServer(options, this._handler.bind(this));
    this._server.on('listening', function () {
        self.emit('listening');
    })
    this._server.on('close', function () {
        self.emit('close');
    })
    this._server.on('error', function (e) {
        self.emit('error', e);
    });
}
869761
function make_node(context, path, type, callback) {
  if(type !== NODE_TYPE_DIRECTORY && type !== NODE_TYPE_FILE) {
    return callback(new Errors.EINVAL('type must be a directory or file', path));
  }

  path = normalize(path);

  var name = basename(path);
  var parentPath = dirname(path);
  var parentNode;
  var parentNodeData;
  var node;

  // Check if the parent node exists
  function create_node_in_parent(error, parentDirectoryNode) {
    if(error) {
      callback(error);
    } else if(parentDirectoryNode.type !== NODE_TYPE_DIRECTORY) {
      callback(new Errors.ENOTDIR('a component of the path prefix is not a directory', path));
    } else {
      parentNode = parentDirectoryNode;
      find_node(context, path, check_if_node_exists);
    }
  }

  // Check if the node to be created already exists
  function check_if_node_exists(error, result) {
    if(!error && result) {
      callback(new Errors.EEXIST('path name already exists', path));
    } else if(error && !(error instanceof Errors.ENOENT)) {
      callback(error);
    } else {
      context.getObject(parentNode.data, create_node);
    }
  }

  // Create the new node
  function create_node(error, result) {
    if(error) {
      callback(error);
    } else {
      parentNodeData = result;
      Node.create({
        guid: context.guid,
        type: type
      }, function(error, result) {
        if(error) {
          callback(error);
          return;
        }
        node = result;
        node.nlinks += 1;
        context.putObject(node.id, node, update_parent_node_data);
      });
    }
  }

  // Update parent node time
  function update_time(error) {
    if(error) {
      callback(error);
    } else {
      var now = Date.now();
      update_node_times(context, parentPath, node, { mtime: now, ctime: now }, callback);
    }
  }

  // Update the parent nodes data
  function update_parent_node_data(error) {
    if(error) {
      callback(error);
    } else {
      parentNodeData[name] = new DirectoryEntry(node.id, type);
      context.putObject(parentNode.data, parentNodeData, update_time);
    }
  }

  // Find the parent node
  find_node(context, parentPath, create_node_in_parent);
}
1230692
def configure_nodes(self):
        """"""
        # Since load balancing runs after server provisioning,
        # the servers should already be created regardless of
        # whether this was a preexisting load balancer or not.
        # We also have the existing nodes, because add_to_inventory
        # has been called already
        required_nodes = self._get_required_nodes()

        log.debug(
                "Matching existing lb nodes to required %s (port %s)"
                % (", ".join(required_nodes), self.backend_port)
                )

        self.consul.match_lb_nodes(
            self.lb_attrs[A.loadbalancer.ID],
            self.lb_attrs[A.loadbalancer.NODES_KEY],
            required_nodes,
            self.backend_port)

        self.lb_attrs = self.consul.lb_details(
                self.lb_attrs[A.loadbalancer.ID]
                )
646746
def make_node(clss, node, *params):
        ''' 
        '''
        if node is None:
            node = clss()

        if node.token != 'PARAMLIST':
            return clss.make_node(None, node, *params)

        for i in params:
            if i is not None:
                node.appendChild(i)

        return node
1045705
def get_node(conn, name):
    '''
    
    '''
    for node in conn.list_servers(per_page=1000):
        if node['name'] == name:
            return node
396897
async def create_server(self, worker, protocol_factory, address=None,
                            sockets=None, idx=0):
        '''
        '''
        cfg = self.cfg
        max_requests = cfg.max_requests
        if max_requests:
            max_requests = int(lognormvariate(log(max_requests), 0.2))
        server = self.server_factory(
            protocol_factory,
            loop=worker._loop,
            max_requests=max_requests,
            keep_alive=cfg.keep_alive,
            name=self.name,
            logger=self.logger,
            server_software=cfg.server_software,
            cfg=cfg,
            idx=idx
        )
        for event in ('connection_made', 'pre_request', 'post_request',
                      'connection_lost'):
            callback = getattr(cfg, event)
            if callback != pass_through:
                server.event(event).bind(callback)
        await server.start_serving(
            sockets=sockets,
            address=address,
            backlog=cfg.backlog,
            sslcontext=self.sslcontext()
        )
        return server
342375
function runServer(cb) {
  function onStdOut(data) {
    const time = new Date().toTimeString();
    const match = data.toString('utf8').match(RUNNING_REGEXP);

    process.stdout.write(time.replace(/.*(\d{2}:\d{2}:\d{2}).*/, '[$1] '));
    process.stdout.write(data);

    if (match) {
      server.stdout.removeListener('data', onStdOut);
      server.stdout.on('data', x => process.stdout.write(x));
      if (cb) {
        cb(null, match[1]);
      }
    }
  }

  if (server) {
    server.kill('SIGTERM');
  }

  server = cp.spawn('node', [serverPath], {
    env: Object.assign({ NODE_ENV: 'development' }, process.env),
    silent: false,
  });

  server.stdout.on('data', onStdOut);
  server.stderr.on('data', x => process.stderr.write(x));
}
912747
function nodeClient (request) {

    var client = require('got');

    return new PromiseObj(function (resolve) {

        var url = request.getUrl();
        var body = request.getBody();
        var method = request.method;
        var headers = {}, handler;

        request.headers.forEach(function (value, name) {
            headers[name] = value;
        });

        client(url, {body: body, method: method, headers: headers}).then(handler = function (resp) {

            var response = request.respondWith(resp.body, {
                status: resp.statusCode,
                statusText: trim(resp.statusMessage)
            });

            each(resp.headers, function (value, name) {
                response.headers.set(name, value);
            });

            resolve(response);

        }, function (error$$1) { return handler(error$$1.response); });
    });
}
343940
function createServer(listen, opt) {

  if (!listen) {
    throw new TypeError('listen required');
  }
  var options = opt || Object.create(null);
  var my = {
    keepalive: Number(options.keepalive) || 2000,
    callback: typeof options.callback === 'function' ? options.callback : false,
    http: false,
    https: false
  };
  if (typeof options.http === 'object') {
    my.http = {
      port: Number(options.http.port) || 3000,
      host: String(options.http.host || '127.0.0.1')
    };
  }
  if (typeof options.https === 'object') {
    my.https = options.https;
    my.https.port = Number(options.https.port) || 3000;
    my.https.host = String(options.https.host || '127.0.0.1');
  }

  var hosts = Object.create(null);
  var server = net.createServer(function(sock) {

    sock.setKeepAlive(true, my.keepalive); // https://en.wikipedia.org/wiki/Keepalive
    sock.on('data', function(buff) {

      if (sock._id) {
        hosts[sock._id] = {
          state: sock.readyState,
          beat: Date.now()
        };
      } else if (buff.length > 1) { // set client id
        var _id = String(buff);
        hosts[_id] = {
          state: sock.readyState,
          beat: Date.now()
        };
        sock._id = _id;
      }
      return;

    }).on('close', function(had_error) {

      if (sock._id) {
        hosts[sock._id] = {
          state: sock.readyState,
          beat: Date.now()
        };
      }
      // error hook [with client id]
      return my.callback !== false ? my.callback(had_error, sock._id) : null;
    });
  });

  if (options.host && typeof listen === 'number') { // tpc only
    server.listen(listen, options.host);
  } else {
    server.listen(listen);
  }

  if (my.http || my.https) {
    var web = function(req, res) {

      var out = '';
      res.setHeader('Content-Type', 'application/json; charset=utf-8');
      var url = decodeURI(req.url);
      url = url.substr(1, url.length);
      if (url === '') {
        out = JSON.stringify(hosts);
      } else if (hosts[url] !== undefined) {
        out = JSON.stringify(hosts[url]);
      } else {
        res.statusCode = 404;
      }
      return res.end(out);
    };
    if (my.http) {
      require('http').createServer(web).listen(my.http.port, my.http.host);
    }
    if (my.https) {
      require('https').createServer(my.https, web).listen(my.https.port,
        my.https.host);
    }
  }

  server._hosts = hosts; // hosts reference
  return server;
}