简体   繁体   English

如何在node.js中导入文件?

[英]how can I import a file in node.js?

I have developed a node.js application and performing some validation with the use of a template. 我已经开发了一个node.js应用程序,并使用模板进行了一些验证。 At the moment this 'template' is a local variable but I would like to store this in a file in my project. 目前,这个“模板”是一个局部变量,但我想将其存储在项目中的文件中。 So this is the validation code: 这是验证代码:

isvalid(req.body,template
   , function(err, validObj) {
        if (!validObj) {
           validJson = false;
        }
});

the template variable looks like this: 模板变量如下所示:

var template={
       type: Object,
       "schema":
       {
          "totalRecords": {type:Number},
          "skip": {type:Number},
          "take": {type:Number}
       }
}

Suppose I have a file which contains the template contents how can I import this into my app? 假设我有一个包含模板内容的文件,如何将其导入到我的应用程序中?

You will need to change this line: 您将需要更改以下行:

var template={

to this: 对此:

module.exports={

And then you can simply do: 然后,您可以简单地执行以下操作:

var template = require('./path/to/template.js');

Note that this is a relative path to your file. 请注意,这是文件的相对路径。

You need to set module.exports because that is the convention NodeJS uses to say "this is what will be returned if you require() this file. 您需要设置module.exports因为这是module.exports所说的约定,“如果您require()这个文件,这就是返回的内容。

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

except that type: Object would need to be "type": "Object" (as a string), to conform to JSON standard (and, of course, without var template = , as Felix Kling correctly notes). 除了该type: Object之外type: Object必须为"type": "Object" (作为字符串),以符合JSON标准(当然,如Felix Kling正确指出的那样,不带var template = )。 If you actually want the Number etc. objects that actually exist in the JS object space, you would need to make it a proper Node module; 如果您实际上想要JS对象空间中实际存在的Number等对象,则需要使其成为适当的Node模块; require syntax stays the same. require语法保持不变。

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

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