Skip to content

Commit 372bf83

Browse files
JacksonTianShigeki Ohtsu
authored and
Shigeki Ohtsu
committed
zlib: make constants keep readonly
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 <[email protected]> Reviewed-By: Johan Bergström <[email protected]> Reviewed-By: Shigeki Ohtsu <[email protected]>
1 parent d726a17 commit 372bf83

File tree

2 files changed

+28
-4
lines changed

2 files changed

+28
-4
lines changed

lib/zlib.js

+12-4
Original file line numberDiff line numberDiff line change
@@ -30,11 +30,15 @@ binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION;
3030
const bkeys = Object.keys(binding);
3131
for (var bk = 0; bk < bkeys.length; bk++) {
3232
var bkey = bkeys[bk];
33-
if (bkey.match(/^Z/)) exports[bkey] = binding[bkey];
33+
if (bkey.match(/^Z/)) {
34+
Object.defineProperty(exports, bkey, {
35+
enumerable: true, value: binding[bkey], writable: false
36+
});
37+
}
3438
}
3539

3640
// translation table for return codes.
37-
exports.codes = {
41+
const codes = {
3842
Z_OK: binding.Z_OK,
3943
Z_STREAM_END: binding.Z_STREAM_END,
4044
Z_NEED_DICT: binding.Z_NEED_DICT,
@@ -46,12 +50,16 @@ exports.codes = {
4650
Z_VERSION_ERROR: binding.Z_VERSION_ERROR
4751
};
4852

49-
const ckeys = Object.keys(exports.codes);
53+
const ckeys = Object.keys(codes);
5054
for (var ck = 0; ck < ckeys.length; ck++) {
5155
var ckey = ckeys[ck];
52-
exports.codes[exports.codes[ckey]] = ckey;
56+
codes[codes[ckey]] = ckey;
5357
}
5458

59+
Object.defineProperty(exports, 'codes', {
60+
enumerable: true, value: Object.freeze(codes), writable: false
61+
});
62+
5563
exports.Deflate = Deflate;
5664
exports.Inflate = Inflate;
5765
exports.Gzip = Gzip;

test/parallel/test-zlib-const.js

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
var common = require('../common');
2+
var assert = require('assert');
3+
4+
var zlib = require('zlib');
5+
6+
assert.equal(zlib.Z_OK, 0, 'Z_OK should be 0');
7+
zlib.Z_OK = 1;
8+
assert.equal(zlib.Z_OK, 0, 'Z_OK should be 0');
9+
10+
assert.equal(zlib.codes.Z_OK, 0, 'Z_OK should be 0');
11+
zlib.codes.Z_OK = 1;
12+
assert.equal(zlib.codes.Z_OK, 0, 'zlib.codes.Z_OK should be 0');
13+
zlib.codes = {Z_OK: 1};
14+
assert.equal(zlib.codes.Z_OK, 0, 'zlib.codes.Z_OK should be 0');
15+
16+
assert.ok(Object.isFrozen(zlib.codes), 'zlib.codes should be frozen');

0 commit comments

Comments
 (0)