zlib: make constants keep readonly
authorJackson Tian <puling.tyq@alibaba-inc.com>
Tue, 7 Apr 2015 05:48:52 +0000 (13:48 +0800)
committerShigeki Ohtsu <ohtsu@iij.ad.jp>
Tue, 7 Apr 2015 14:38:55 +0000 (23:38 +0900)
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 <info@bnoordhuis.nl>
Reviewed-By: Johan Bergström <bugs@bergstroem.nu>
Reviewed-By: Shigeki Ohtsu <ohtsu@iij.ad.jp>
lib/zlib.js
test/parallel/test-zlib-const.js [new file with mode: 0644]

index 14ccf8f..48bb70c 100644 (file)
@@ -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 (file)
index 0000000..df9ca3d
--- /dev/null
@@ -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');