code-this

Code-this is node.js module that converts JavaScript variables into source codes. Unlike JSON.stringify, code-this also deals with reference(object) types of variables.

Code-this

Code-this is the node.js module that converts JavaScript variables into source codes.

Unlike JSON.stringify, code-this also deals with reference(object) types of variables.

npm install code-this --save
var code = require('code-this');
var a = {afunction(n){return n;}, b: 1, c: 3};
 
code(a, null, 2); // 1 

Expression {1} will return:

'{\n  \'a\'function (n){return n;},\n  \'b\': 1,\n  \'c\': 3\n}'

So you can use code-this to save your javascript variables into a file:

require('fs').writeFileSync(
    'output.js', 
    'module.exports = ' + code(a, null, 2) + ';';
);

Then 'output.js' will look like:

module.exports = {
  'a'function (n){return n;},
  'b': 1,
  'c': 3
};

The subject to be converted

The replacer argument acts just like the second parameter of JSON.stringify.

The space argument acts just like the third parameter of JSON.stringify.

  • Code-this can't deal with recursive objects or arrays SO FAR.
  • space parameter could not affect the code indent inside functions.
  • Code-this could not deal with variable scope so far.

Those issues or tasks which should be done to enhance the module might be fixed in the future. Or there will be a million thanks if you fork and contribute ~~