theParameters.forEach(function(par,index) {
		if (par===null) {
			self.pushIntBE(-1>>>0,4);
		} else {
			par=String(par);
			self.pushIntBE(Buffer.byteLength(par,'utf8'),4);
			self.pushString(par,'utf8');
		}
	});
Example #2
0
    this._write = function (chans, json) {
      debug("Writing data: " + json);

      var bufA = new Buffer(Buffer.byteLength(json) + mode_header_width + header_size + (chan_id_width * chans.length),'binary');

      var bufB = new Buffer(pack('Cnn', MODE_MESG, chans.length, Buffer.byteLength(json)),'binary');
      bufB.copy(bufA,0,0);

      var bufD = new Buffer(chans.length * chan_id_width, 'binary');
      for (var i = 0; i < chans.length; i++) {
        (new Buffer(pack('N', chans[i].getId()), 'binary')).copy(bufD, i * chan_id_width, 0)
      };
      bufD.copy(bufA, bufB.length, 0);

      var bufC = new Buffer(json);
      bufC.copy(bufA,bufB.length + bufD.length,0);
      doWrite(bufA);
    }
Example #3
0
util.sendjson = function(res,obj) {
  var objstr = JSON.stringify(obj)
  res.writeHead(200,{
    'Content-Type': 'application/json',
    'Cache-Control': 'private, max-age=0, no-cache, no-store',
    "Content-Length": buffer.Buffer.byteLength(objstr) 
  })
  res.end( objstr )
}
Example #4
0
Notification.prototype.isValid = function () {
    if (!this.device || !this.device.isValid()) return false;

    var normalized = this.normalizedPayload();
    if (Buffer.byteLength(JSON.stringify(normalized), this.encoding) > 256) return false;
    if (!normalized.aps.alert && !normalized.aps.sound && !normalized.aps.badge) return false;

    return true;
}
Example #5
0
function post(path, obj, onend) {
	let url = 'http://' + domain + path,
		retry = 3,
		postData = querystring.stringify(obj),
		opt = {
			hostname: domain,
			port: 80,
			path: path,
			method: 'POST',
			headers: {
				'Referer': 'http://' + domain + path,
				'Content-Type': 'application/x-www-form-urlencoded',
				'Content-Length': Buffer.byteLength(postData)
			}
		};

	echo('POST ' + url + ' : ' + postData)
	run()
	function run() {
		let req = http.request(opt, function ready(res) {
			var chunks = [];
			res.on('data', function(chunk) {
				chunks.push(chunk);
			});

			res.on('end', function() {
				let body,
					ct = charset(res.headers['content-type']);

				if (ct != 'utf8')
					body = iconv.decode(Buffer.concat(chunks), ct);
				else
					body = Buffer.concat(chunks).toString();
				if (body.indexOf('�') == -1)
					onend((new JSDOM(body, { url: url })).window.document)
				else {
					retry--
					if (!retry)
						error(`invalid encoding GET ${url}: ${e.message}`);
					echo('retry')
					setTimeout(run, 500)
				}
			});
		});

		req.on('error', function(e) {
			retry--
			if (!retry)
				error(`problem POST ${url}: ${e.message}`);
			echo('retry')
			setTimeout(run, 2000)
		});

		req.write(postData);
		req.end();
	}
}
Example #6
0
  }).reduce(function(prev, key) {
    var nameLen = Buffer.byteLength(key),
        valueLen = Buffer.byteLength(nvs[key].toString());

    buff[prev] = (nameLen >> 8) & 255;
    buff[prev + 1] = nameLen & 255;
    buff.write(key.toString().toLowerCase(), prev + 2);

    prev += 2 + nameLen;

    buff[prev] = (valueLen >> 8) & 255;
    buff[prev + 1] = valueLen & 255;
    buff.write(nvs[key].toString(), prev + 2);

    prev += 2 + valueLen;

    return prev;
  }, 2);
Example #7
0
        .pipe(es.mapSync(function (data) {

            this.setHeaders({

                'Content-Length': Buffer.byteLength(data),
                'Imitator-Response-From': 'Target'
            });

            return data;
        }.bind(this)))
Example #8
0
	fs.readdir(parentDirectory, function(error, files) {
		var body = formatBody(parentDirectory, files);
		res.writeHead(200, {
			"Content-Type": "text/html;charset=utf-8",
			"Content-Length": Buffer.byteLength(body, 'utf8'),
			"Server": "NodeJs(" + process.version + ")"
		});
		res.write(body);
		res.end();
	});
Example #9
0
Client.prototype.query = function () {
    var query = "*" + arguments.length.toString() + "\r\n";
    for (var i = 0; i < arguments.length; i++) {
	var arg = arguments[i].toString();
	query += ("$" + Buffer.byteLength(arg, "utf8") + "\r\n" +
		  arg + "\r\n");
    }
    if (this.readyState === 'closed') this._reconnect();
    this.buf(query);
};
 fs.write(fd, data, 0, 'utf8', function(err, written) {
   console.log('write done');
   if (err) throw err;
   assert.equal(Buffer.byteLength(expected), written);
   fs.closeSync(fd);
   found = fs.readFileSync(fn, 'utf8');
   console.log('expected: "%s"', expected);
   console.log('found: "%s"', found);
   fs.unlinkSync(fn);
 });
Example #11
0
        "should download file successfuly": function (err, file) {
          assert.isNull(err);
          assert.assertFile(file);
          assert.assertNock(nock);

          assert.equal(file.name, testContext.file.name);
          assert.equal(testContext.fileContents,
                       helpers.loadFixture('fillerama.txt'));
          assert.equal(file.size, Buffer.byteLength(testContext.fileContents));
        }
Example #12
0
        "should upload file successfuly": function (err, ok) {
          assert.isNull(err);
          assert.ok(ok);
          assert.assertNock(nock);

          testContext.file = {
            name: 'test-file.txt',
            size: Buffer.byteLength(helpers.loadFixture('fillerama.txt'))
          };
        }
Example #13
0
//如果文件找不到,显示404错误
function write404(req, res) {
	var body = "文件不存在:-(";
	res.writeHead(404, {
		"Content-Type": "text/html;charset=utf-8",
		"Content-Length": Buffer.byteLength(body, 'utf8'),
		"Server": "NodeJs(" + process.version + ")"
	});
	res.write(body);
	res.end();
}
// TODO: test without using express

// TODO: move to seneca-web
function sendjson( code, res, out ) {
  // TODO: need killcircles
  var outjson = JSON.stringify(out)
  res.writeHead( code, {
    'Content-Type':   'application/json',
    'Cache-Control':  'private, max-age=0, no-cache, no-store',
    'Content-Length': buffer.Buffer.byteLength(outjson)
  })
  res.end( outjson )
}
Example #15
0
File: http.js Project: ehaas/node
OutgoingMessage.prototype.end = function (data, encoding) {
  var ret;

  var hot = this._headerSent === false
         && typeof(data) === "string"
         && data.length > 0
         && this.output.length === 0
         && this.connection.writable
         && this.connection._outgoing[0] === this
          ;

  if (hot) {
    // Hot path. They're doing
    //   res.writeHead();
    //   res.end(blah);
    // HACKY.
    if (this.chunkedEncoding) {
      var l = Buffer.byteLength(data, encoding).toString(16);
      ret = this.connection.write( this._header
                                 + l
                                 + CRLF
                                 + data
                                 + "\r\n0\r\n\r\n"
                                 , encoding
                                 );
    } else {
      ret = this.connection.write(this._header + data, encoding);
    }
    this._headerSent = true;

  } else if (data) {
    // Normal body write.
    ret = this.write(data, encoding);
  }

  if (!hot) {
    if (this.chunkedEncoding) {
      ret = this._send('0\r\n\r\n'); // Last chunk.
    } else if (!data) {
      // Force a flush, HACK.
      ret = this._send('');
    }
  }

  this.finished = true;

  // There is the first message on the outgoing queue, and we've sent
  // everything to the socket.
  if (this.output.length === 0 && this.connection._outgoing[0] === this) {
    debug('outgoing message end. shifting because was flushed');
    this.connection._onOutgoingSent();
  }

  return ret;
};
Example #16
0
Writer.prototype.getBodyRawBufferLength = function(raw) {
	if (typeof raw == 'string')
	{
		var size = buffer.Buffer.byteLength(raw,'utf8') + 2;
	}
	else
	{
		var size = raw.length + 2;
	}
	return raw.length >= 0x100 ? size + 2 : size;
	};
Example #17
0
/**
 * Encode a MIDI chunk
 *
 * @param {String} type - Chunk type
 * @param {Buffer} data - Chunk data
 * @return {Buffer} Encoded chunk
 */
function encodeChunk(type, data) {
    var cursor = new BufferCursor(new buffer.Buffer(
        buffer.Buffer.byteLength(type) + 4 + data.length
    ));
    
    cursor.write(type);
    cursor.writeUInt32BE(data.length);
    cursor.copy(data);
    
    return cursor.buffer;
}
    var _updateGist = function (gistId, results, date, callback) {
        var newGistFileName = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + '.json';
        var newGistFileObj = {};

        newGistFileObj[newGistFileName] = {
            content: JSON.stringify(results, null, '\t')
        };

        var gistCreatePostData = {
            'files': newGistFileObj
        };

        var gistCreatePostString = JSON.stringify(gistCreatePostData);

        var gistCreatePostOptions = {
            host: 'api.github.com',
            port: 443,
            path: '/gists/' + gistId,
            method: 'PATCH',
            headers: {
                'Authorization': 'token ' + cfg.github_token,
                'Content-Length': Buffer.byteLength(gistCreatePostString),
                'Content-Type': 'application/json; charset=UTF-8'
            }
        };

        var req = http.request(gistCreatePostOptions, function (res) {
            res.setEncoding('utf8');
            var statusCode = res.statusCode;
            var headers = res.headers;

            var output = '';
            res.on('data', function (chunk) {
                output += chunk;
            });

            res.on('end', function () {
                if(statusCode === 200) {
                    callback(null);
                }
                else {
                    callback({code: statusCode, headers: headers, msg: output});
                }
            });
        });

        req.on('error', function (err) {
            callback(err);
        });

        _writeStringIntoRequest(gistCreatePostString, req);

        req.end();
    };
Example #19
0
var restRequest = function(options, callback){
    callback = callback || noop;
    options = options || {};

    // set protocol to HTTP or HTTPS
    options.protocol = options.protocol || "http";
    options.protocol = (options.protocol.toLowerCase() == "http") ? "http" : "https";
    var protocol = (options.protocol == "http") ? http : https;

    // automatically manage body submit & set content length if not specified
    if((typeof options.body != "undefined") && (!options.headers["Content-Length"])){
        options.headers["Content-Length"] = Buffer.byteLength( options.body, 'utf8' );
    }

    // if we still don't have have content length, set to zero
    if(typeof options.headers["Content-Length"] == "undefined") options.headers["Content-Length"] = 0;

    var submitBody = options.body;

    // cleanup options from custom vars
    delete options.protocol;
    delete options.body;

    var req = protocol.request(options, function(res) {

        var body = [];
        res.on('data', function(d) {
            body.push(d);
        });
        res.on('end', function() {

            body = Buffer.concat(body).toString();

            if(res.headers["content-type"]) {
                if (res.headers["content-type"].toLowerCase().indexOf("application/json") !== -1) {
                    body = JSON.parse(body);
                }
            }

            if(res.statusCode >= 400) {
                callback(res.statusCode, body);
            } else {
                callback(null, body);
            }
        });
    });

    req.on('error', function(e) {
        callback(e);
    });

    if(submitBody) req.write(submitBody);
    req.end();
};
Example #20
0
 fs.write(fd, expected, 0, 'utf8', common.mustCall(function(err, written) {
   console.log('write done');
   if (err) throw err;
   assert.equal(Buffer.byteLength(expected), written);
   fs.closeSync(fd);
   const found = fs.readFileSync(fn2, 'utf8');
   console.log('expected: "%s"', expected);
   console.log('found: "%s"', found);
   fs.unlinkSync(fn2);
   assert.strictEqual(expected, found);
 }));
Example #21
0
    child.stderr.on('data', function onChildStderr(chunk) {
      var encoding = child.stderr._readableState.encoding;
      stderrLen += encoding ? Buffer.byteLength(chunk, encoding) : chunk.length;

      if (stderrLen > options.maxBuffer) {
        ex = new ERR_CHILD_PROCESS_STDIO_MAXBUFFER('stderr');
        kill();
      } else {
        _stderr.push(chunk);
      }
    });
Example #22
0
function write_(msg, chunk, encoding, callback, fromEnd) {
  if (msg.finished) {
    const err = new errors.Error('ERR_STREAM_WRITE_AFTER_END');
    nextTick(msg.socket && msg.socket[async_id_symbol],
             writeAfterEndNT.bind(msg),
             err,
             callback);

    return true;
  }

  if (!msg._header) {
    msg._implicitHeader();
  }

  if (!msg._hasBody) {
    debug('This type of response MUST NOT have a body. ' +
          'Ignoring write() calls.');
    return true;
  }

  if (!fromEnd && typeof chunk !== 'string' && !(chunk instanceof Buffer)) {
    throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'first argument',
                               ['string', 'Buffer']);
  }


  // If we get an empty string or buffer, then just do nothing, and
  // signal the user to keep writing.
  if (chunk.length === 0) return true;

  if (!fromEnd && msg.connection && !msg.connection.corked) {
    msg.connection.cork();
    process.nextTick(connectionCorkNT, msg.connection);
  }

  var len, ret;
  if (msg.chunkedEncoding) {
    if (typeof chunk === 'string')
      len = Buffer.byteLength(chunk, encoding);
    else
      len = chunk.length;

    msg._send(len.toString(16), 'latin1', null);
    msg._send(crlf_buf, null, null);
    msg._send(chunk, encoding, null);
    ret = msg._send(crlf_buf, null, callback);
  } else {
    ret = msg._send(chunk, encoding, callback);
  }

  debug('write ret = ' + ret);
  return ret;
}
Example #23
0
      }, function (err, file) {
        should.not.exist(err);
        should.exist(file);

        file.name.should.equal(context.file.name);
        context.fileContents.should.equal(fillerama);
        file.size.should.equal(Buffer.byteLength(context.fileContents));

        server && server.done();
        done();
      });
Example #24
0
    child.stderr.on('data', function onChildStderr(chunk) {
      stderrLen += encoding ? Buffer.byteLength(chunk, encoding) : chunk.length;

      if (stderrLen > options.maxBuffer) {
        ex = new Error('stderr maxBuffer exceeded');
        kill();
      } else if (encoding) {
        _stderr += chunk;
      } else {
        _stderr.push(chunk);
      }
    });
Example #25
0
            req.seneca.act( req.body, function( err, out ){
              if( err ) return next(err);
        
              var outjson = _.isUndefined(out) ? '{}' : JSON.stringify(out)

              res.writeHead(200,{
                'Content-Type':   'application/json',
                'Cache-Control':  'private, max-age=0, no-cache, no-store',
                'Content-Length': buffer.Buffer.byteLength(outjson) 
              })
              res.end( outjson )
            })
Example #26
0
    }, function (statusCode, body) {
      let routeId = JSON.parse(body).ideal.routeId;

      let url = uri.parse(clientToken.braintree_api.url);
      let token = clientToken.braintree_api.access_token;
      let options = {
        host: url.hostname,
        port: url.port,
        method: 'POST',
        path: '/ideal-payments',
        headers: {
          'Content-Type': 'application/json',
          'Braintree-Version': '2015-11-01',
          Authorization: `Bearer ${token}`
        }
      };

      /* eslint-disable camelcase */
      let payload = {
        issuer: 'RABONL2u',
        order_id: 'ABC123',
        amount: amount,
        currency: 'EUR',
        route_id: routeId,
        redirect_url: 'https://braintree-api.com'
      };
      /* eslint-enable camelcase */

      let requestBody = JSON.stringify(Util.convertObjectKeysToUnderscores(payload));

      options.headers['Content-Length'] = Buffer.byteLength(requestBody).toString();

      let req = https.request(options);

      req.on('response', response => {
        let body = '';

        response.on('data', responseBody => {
          body += responseBody;
        });
        response.on('end', () => {
          let json = JSON.parse(body);

          callback(json.data.id);
        });
        return response.on('error', err => console.log(`Unexpected response error: ${err}`));
      });

      req.on('error', err => console.log(`Unexpected request error: ${err}`));

      req.write(requestBody);
      return req.end();
    });
Example #27
0
    child.stdout.on('data', function onChildStdout(chunk) {
      stdoutLen += encoding ? Buffer.byteLength(chunk, encoding) : chunk.length;

      if (stdoutLen > options.maxBuffer) {
        ex = new ERR_CHILD_PROCESS_STDIO_MAXBUFFER('stdout');
        kill();
      } else if (encoding) {
        _stdout += chunk;
      } else {
        _stdout.push(chunk);
      }
    });
exports.signBody = function signBody(req, options) {
  if (!options) options = {};

  if (typeof options.key !== 'string') {
    throw new TypeError('`key` is a required argument for aws-signature');
  }

  if (typeof options.keyId !== 'string') {
    throw new TypeError('`keyId` is a required argument for aws-signature');
  }

  var signatureString = [
        req.method, '\n',
        this.serversUrl, '\n',
        '/', '\n'
      ],
      query = req.body;

  query.AWSAccessKeyId = options.keyId;
  query.SignatureMethod = 'HmacSHA256';
  query.SignatureVersion = 2;
  query.Version = this.version;
  query.Timestamp = new Date(+new Date + 36e5 * 30).toISOString();

  Object.keys(query).sort().forEach(function (key, i) {
    if (i !== 0) signatureString.push('&');
    signatureString.push(encodeURIComponent(key), '=', encodeURIComponent(query[key]));
  });

  var toSign = signatureString.join('');

  // Crappy code, but AWS seems to need it
  toSign = toSign.replace(/!/g, '%21');
  toSign = toSign.replace(/'/g, '%27');
  toSign = toSign.replace(/\*/g, '%2A');
  toSign = toSign.replace(/\(/g, '%28');
  toSign = toSign.replace(/\)/g, '%29');

  query.Signature = crypto.createHmac(
      'sha256',
      options.key
  ).update(toSign).digest('base64');

  req.path.push('?Action=' + query.Action);
  delete query.Action;

  req.body = Object.keys(query).sort().map(function (key) {
    return encodeURIComponent(key) + '=' + encodeURIComponent(query[key]);
  }).join('&');

  req.headers['Content-Type'] = 'application/x-www-form-urlencoded';
  req.headers['Content-Length'] = Buffer.byteLength(req.body);
};
Example #29
0
http.ServerResponse.prototype.send = function(body, headers, status){
    // Allow status as second arg
    if (typeof headers === 'number') {
        status = headers,
        headers = null;
    }

    // Defaults
    status = status || 200;
    headers = headers || {};

    // Determine content type
    switch (typeof body) {
        case 'number':
            if (!this.headers['Content-Type']) {
                this.contentType('.txt');
            }
            body = http.STATUS_CODES[status = body];
            break;
        case 'string':
            if (!this.headers['Content-Type']) {
                this.contentType('.html');
            }
            break;
        case 'object':
            if (body instanceof Buffer) {
                if (!this.headers['Content-Type']) {
                    this.contentType('.bin');
                }
            } else {
                if (!this.headers['Content-Type']) {
                    this.contentType('.json');
                }
                body = JSON.stringify(body);
            }
            break;
    }

    // Populate Content-Length
    if (!this.headers['Content-Length']) {
        this.header('Content-Length', body instanceof Buffer
            ? body.length
            : Buffer.byteLength(body));
    }

    // Merge headers passed
    utils.merge(this.headers, headers);

    // Respond
    this.writeHead(status, this.headers);
    this.end(body);
};
Example #30
0
/**
 * Sends the response with the css to the client.
 *
 * @param {HTTP request} req the request from the client
 * @param {HTTP response} res the HTTP response for the client request
 * @param {Integer} maxAge
 * @param {String} css the content of the css after compile and scope
 * @param {Object} compiledCSS cached object of component's CSS
 */
function sendResponse(req, res, maxAge, css, compiledCSS) {
    var opts = routerUtils.setResourceHeaders(req, res, maxAge, compiledCSS.lastModified,
        'text/css; charset=UTF-8', Buffer.byteLength(css, 'utf8'));

    if (opts.sendBody) {
        if (opts.start && opts.end) {
            var buf = new Buffer(css, 'utf8');
            res.end(buf.toString('utf8', opts.start, opts.end + 1));
        } else {
            res.end(css);
        }
    }
}