Search code examples
javascriptnode.jsrequire

Function in array is null in js


I am having trouble with writing functions in arrays.

Here is what happens:

config.js

module.exports = {
  transformers: {
    reshape: {
      parser: 'sugarml',
      plugins: [
        // require('reshape-custom-elements')({defaultTag: 'span'})
        function () {
          console.log(arguments)
        }
      ]
    }
  }
}

Then in the node REPL

var config = require('./config.js')

console.log(JSON.stringify(config.transformers, null, 2))

It outputs

{
  "reshape": {
    "parser": "sugarml",
    "plugins": [
      null
    ]
  },
  "uglify-js": {
    "mangle": {
      "toplevel": true
    }
  },
  "rollup": {
    "format": "es",
    "plugins": {
      "rollup-plugin-node-resolve": {},
      "rollup-plugin-commonjs": {}
    }
  }
}

I am confused why plugins is [null]


Solution

  • You cannot serialize a function in JSON. From MDN:

    If undefined, a function, or a symbol is encountered during conversion it is either omitted (when it is found in an object) or censored to null (when it is found in an array). JSON.stringify can also just return undefined when passing in "pure" values like JSON.stringify(function(){}) or JSON.stringify(undefined).

    source

    I would question storing configuration like this in JSON, but if you really need to you can consider something like serialize-javascript that will handle the serialization of functions.