Skip to content

Commit

Permalink
zlib: make constants keep readonly
Browse files Browse the repository at this point in the history
In zlib module, a dozen constants were exported to user land,
If user change the constant, maybe lead unexcepted error.

Make them readonly and freezon.

PR-URL: #1361
Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
Reviewed-By: Johan Bergström <bugs@bergstroem.nu>
Reviewed-By: Shigeki Ohtsu <ohtsu@iij.ad.jp>
  • Loading branch information
JacksonTian authored and Shigeki Ohtsu committed Apr 7, 2015
1 parent d726a17 commit 372bf83
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
16 changes: 12 additions & 4 deletions lib/zlib.js
Expand Up @@ -30,11 +30,15 @@ binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION;
const bkeys = Object.keys(binding);
for (var bk = 0; bk < bkeys.length; bk++) {
var bkey = bkeys[bk];
if (bkey.match(/^Z/)) exports[bkey] = binding[bkey];
if (bkey.match(/^Z/)) {
Object.defineProperty(exports, bkey, {
enumerable: true, value: binding[bkey], writable: false
});
}
}

// translation table for return codes.
exports.codes = {
const codes = {
Z_OK: binding.Z_OK,
Z_STREAM_END: binding.Z_STREAM_END,
Z_NEED_DICT: binding.Z_NEED_DICT,
Expand All @@ -46,12 +50,16 @@ exports.codes = {
Z_VERSION_ERROR: binding.Z_VERSION_ERROR
};

const ckeys = Object.keys(exports.codes);
const ckeys = Object.keys(codes);
for (var ck = 0; ck < ckeys.length; ck++) {
var ckey = ckeys[ck];
exports.codes[exports.codes[ckey]] = ckey;
codes[codes[ckey]] = ckey;
}

Object.defineProperty(exports, 'codes', {
enumerable: true, value: Object.freeze(codes), writable: false
});

exports.Deflate = Deflate;
exports.Inflate = Inflate;
exports.Gzip = Gzip;
Expand Down
16 changes: 16 additions & 0 deletions test/parallel/test-zlib-const.js
@@ -0,0 +1,16 @@
var common = require('../common');
var assert = require('assert');

var zlib = require('zlib');

assert.equal(zlib.Z_OK, 0, 'Z_OK should be 0');
zlib.Z_OK = 1;
assert.equal(zlib.Z_OK, 0, 'Z_OK should be 0');

assert.equal(zlib.codes.Z_OK, 0, 'Z_OK should be 0');
zlib.codes.Z_OK = 1;
assert.equal(zlib.codes.Z_OK, 0, 'zlib.codes.Z_OK should be 0');
zlib.codes = {Z_OK: 1};
assert.equal(zlib.codes.Z_OK, 0, 'zlib.codes.Z_OK should be 0');

assert.ok(Object.isFrozen(zlib.codes), 'zlib.codes should be frozen');

0 comments on commit 372bf83

Please sign in to comment.