简体   繁体   English

如何从一些外部文件导入nodejs中的模块

[英]How to import module in nodejs from some external file

I have this file indexjs where I am exporting data 我在导出数据的地方有这个文件indexjs

exports.updateMobileNumber = updateMobileNumber;

and in my appjs I am importing it. 在我的appjs中,我正在导入它。

var index = require('./../helpers/index');

Now another file mainjs is on external URL like 现在另一个文件mainjs在外部URL上,例如

https://github.com/../models/catalog/main.js

How to import this file in my appjs 如何在我的app.js中导入此文件

I don't want to download the file as it has its own server. 我不想下载该文件,因为它具有自己的服务器。 Is it possible to make http request from one nodejs to another nodejs running simultaneously so that I get the required value. 是否可以从一个nodejs向同时运行的另一个nodejs发出http请求,以便获得所需的值。 If yes, please help how to do it! 如果是,请帮助该怎么做!

I have 1st node running at 3000 and another running at 3003, what should be the next step? 我有第一个节点运行在3000,另一个节点运行在3003,下一步应该是什么?

NPM is designed for you to install and manage remote modules. NPM专为您安装和管理远程模块而设计。 Modules must be locally accessible and installed when a NodeJS instance is started up. 启动NodeJS实例时,必须在本地可访问和安装模块。

If you require a module not known to your package.json file, an error will be thrown. 如果您require package.json文件未知的模块,则将引发错误。

Edit: require is synchronous, so it can't load non-local files (which would be an asynchronous operation). 编辑: require是同步的,因此它不能加载非本地文件(这将是异步操作)。 You could load data asynchronously though, using request . 不过,您可以使用request异步加载数据。

Short answer for the bare question (as it's written in title): 简短问题的简短答案(如标题所示):

Download the file and place it inside your project, so you can use it with require. 下载文件并将其放置在项目中,以便可以与require一起使用。

-- -

You should think about: (as already mentioned in a lot of comments): 您应该考虑:(正如很多评论中已经提到的那样):

  1. If your remote file is data only (most of the time json) it's a convenient and correct way requesting the file via http, save it and then use it with require again! 如果您的远程文件仅是数据(大多数情况下为json),则这是通过http请求文件的一种方便且正确的方法,将其保存,然后再次与require一起使用!

    more about http inside node: 有关节点内部http的更多信息:

  2. If the remote file is not about data only and you thought about executing remote code - it's the wrong way! 如果远程文件不仅仅涉及数据,而且您考虑过执行远程代码-这是错误的方法! think about it! 考虑一下! your remote file is in your case a kind of a "vendor library / util / helper" which you should implement strictly in awareness. 在您的情况下,您的远程文件是一种“供应商库/ util / helper”,您应该严格执行该文件。 (keywords: npm, modularization, vendors, helpers) (关键字:npm,模块化,供应商,帮助者)

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

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