javascript 你如何导入非 node.js 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4662851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 14:28:15  来源:igfitidea点击:

How do you import non-node.js files?

javascriptnode.js

提问by Will03uk

How do I load external js files that don't fit the node.js format. I am trying to import the json serialize library. How can I do this?

如何加载不符合 node.js 格式的外部 js 文件。我正在尝试导入 json 序列化库。我怎样才能做到这一点?

回答by nicolaskruchten

2 answers...

2 个回答...

1) the JSON object is built-in to node.js, so you can just call JSON.parse() and JSON.stringify(), there is no need to import external code for this particular case.

1) JSON 对象内置在 node.js 中,因此您只需调用 JSON.parse() 和 JSON.stringify(),对于这种特殊情况,无需导入外部代码。

2) to import external code, node.js follows the CommonJS module specification and you can use require()

2)引入外部代码,node.js遵循CommonJS模块规范,可以使用require()

so if you have a file called external.js (in the same directory as the rest of your code):

因此,如果您有一个名为 external.js 的文件(与您的其余代码在同一目录中):

this.hi = function(x){ console.log("hi " + x); }

and from node you do:

从节点你做:

var foo = require("./external");
foo.hi("there");

you will see the output hi there

你会看到输出 hi there

回答by RandomEtc

If you trust the code (I mean, reallytrust the code) then you can evalit:

如果您信任代码(我的意思是,真的信任代码),那么您可以eval

eval(require('fs').readFileSync('somefile.js', 'utf8')); 

I wouldn't recommend doing this with remote code (because it could change without your knowledge) but if you have a local copy of something then it should be fine.

我不建议使用远程代码执行此操作(因为它可能会在您不知情的情况下更改),但是如果您有某物的本地副本,那么应该没问题。

回答by Ivo Wetzel

Write wrappers or change the code.

编写包装器或更改代码。

What should automagically make it work? How's Node supposed to know which functions should get exported or not?

什么应该自动使它工作?Node 应该如何知道哪些函数应该被导出?

All you can do is to adjust the code to match the Common JS standard, but before you do that, check the API Docsand the Modules Pageson the Node.js Wiki, to see whether someone already did the job for you :)

您所能做的就是调整代码以匹配 Common JS 标准,但在此之前,请查看Node.js Wiki 上的API 文档模块页面,看看是否有人已经为您完成了这项工作:)

If you write code yourself that should work in a Browser and Node.js you can use a wrapper like the following one:

如果您自己编写应该在浏览器和 Node.js 中工作的代码,您可以使用如下包装器:

(function(node) {
    // Your Awesome code here
    if (node) {
        exports.foo = ...

    } else {
        window.foo = ...
    }

})((function(){return ('' + this).slice(8, -1) !== 'DOMWindow';})());