简体   繁体   English

node.js需要json文件

[英]node.js require of a json file

I am trying to require() this JSON file. 我正在尝试require()这个JSON文件。

{
    "info" : function (request) {
        var i = "<pre>";
        i+= "current working directory: " + process.cwd() + "\n";
        i+="request url: " + request.url + "\n";
        i+= "</pre>";
        return i;
    }
}

Using this line 使用这条线

var render = require('./render.json');

But I get an exception from the JSON file of : Unexpected token u 但是我从JSON文件中得到一个异常:意外令牌u

What am I doing wrong please ? 请问我做错了什么?

The following works in a browser. 以下在浏览器中有效。 Which I would expect, since a function is a object. 我会期望的,因为函数是对象。 And nodejs docs suggests JSON can be a module: http://nodejs.org/api/modules.html#modules_file_modules 并且nodejs文档建议JSON可以是一个模块: http ://nodejs.org/api/modules.html#modules_file_modules

<html>
<head>
</head>
<body>

<script>

  var a = {
    "b" : function(msg){
      alert(msg);
    }
  }

  a.b("Hello");

</script>

</body>
</html>

JSON is purely meant to be a data description language. JSON纯粹是一种数据描述语言。 Per http://www.json.org , it is a "lightweight data-interchange format." 根据http://www.json.org ,它是“轻量级数据交换格式”。 - not a programming language. -不是编程语言。

you cannot have function inside your JSON and use node. 您不能在JSON中使用函数并使用节点。

{
    "error": [
        function (request) {

        }
    ]

}

Is it valid to define functions in JSON results? 在JSON结果中定义函数是否有效?

The way I have gotten around this is to create a js file instead of a json file: 我解决这个问题的方法是创建一个js文件而不是json文件:
config.js config.js

exports.config = [
    {
        "foo": 12,
        "bar": 10,
        "baz": function(a){
            console.dir(a);
        }
    }
]

then within node: 然后在节点内:

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

 var a = {
   m: 'something',
   o: 'somethingelses'
 }

 config[0].baz(a);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM