简体   繁体   中英

Browserify and extending Buffer.prototype

I'm trying to use some node.js modules in a chrome packaged app. (I'm talking to the serial port)

I've extended the Buffer prototype to add the 'indexOf' method.

I'm using Browserify, and what seems to be happening is it doesn't pick up my prototype extension. My Buffers end up being Uint8Arrays without indexOf available.

Is there a trick to extending Buffer in a way that Browserify will pick up?

My extension looks like this, but I've also tried npm packages that do the same thing (the below code was lifted from one), so I think the problem isn't necessarily in my code:

Buffer.indexOf = function(haystack, needle, i) {
    if (!Buffer.isBuffer(needle)) {
        needle = new Buffer(needle);
    }

if (typeof i === 'undefined') { 
    i = 0;
}

var l = haystack.length - needle.length + 1;

while (i < l) {
    var good = true;
    for (var j = 0, n = needle.length; j < n; j++) {
        if (haystack.get(i + j) !== needle.get(j)) {
            good = false;
            break;
        }
    }
    if (good) {
        return i;
    }
    i++;
}

return -1;
};

Buffer.prototype.indexOf = function(needle, i) {
    return Buffer.indexOf(this, needle, i);
}

Is there a trick to extending Buffer in a way that Browserify will pick up?

I doubt it, since browserify has its own implementation for Buffer.

But what's worse is that any other module that uses your module is affected by your change to Buffer.prototype . Instead of extending the prototype of a core component, you should create a helper function instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM