From 372bf83818fd87bae5ad7cedadfa121ddc5d4345 Mon Sep 17 00:00:00 2001 From: Jackson Tian Date: Tue, 7 Apr 2015 13:48:52 +0800 Subject: [PATCH] zlib: make constants keep readonly MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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: https://github.com/iojs/io.js/pull/1361 Reviewed-By: Ben Noordhuis Reviewed-By: Johan Bergström Reviewed-By: Shigeki Ohtsu --- lib/zlib.js | 16 ++++++++++++---- test/parallel/test-zlib-const.js | 16 ++++++++++++++++ 2 files changed, 28 insertions(+), 4 deletions(-) create mode 100644 test/parallel/test-zlib-const.js diff --git a/lib/zlib.js b/lib/zlib.js index 14ccf8f9597731..48bb70cb31415a 100644 --- a/lib/zlib.js +++ b/lib/zlib.js @@ -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, @@ -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; diff --git a/test/parallel/test-zlib-const.js b/test/parallel/test-zlib-const.js new file mode 100644 index 00000000000000..df9ca3d50097ad --- /dev/null +++ b/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');