Skip to content
This repository has been archived by the owner on Dec 4, 2018. It is now read-only.

Check whether or not Buffer and Int32Array are present and support buf[index] #23

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 23 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,25 @@ var Parser = require('jsonparse')

*/

/*

In order to use jsonparse we need something that supports buf[index]
so check what works in the current environment.

*/

var isSafeToUseBuffer =
('undefined' !== typeof Buffer) &&
(new Buffer('X')[0] === 88)

var isSafeToUseInt32Array =
('undefined' !== typeof Int32Array) &&
function(){
var buf = new Int32Array(1)
buf[0] = 42
return buf[0] === 42
}()

exports.parse = function (path) {

var stream = new Stream()
Expand Down Expand Up @@ -72,12 +91,12 @@ exports.parse = function (path) {
stream.writable = true
stream.write = function (chunk) {
if('string' === typeof chunk) {
if ('undefined' === typeof Buffer) {
if (isSafeToUseBuffer) {
chunk = new Buffer(chunk)
} else {
var buf = new Array(chunk.length)
for (var i = 0; i < chunk.length; i++) buf[i] = chunk.charCodeAt(i)
chunk = new Int32Array(buf)
} else {
chunk = new Buffer(chunk)
chunk = isSafeToUseInt32Array ? new Int32Array(buf) : buf
}
}
parser.write(chunk)
Expand Down