Sumit Sahay
Sumit Sahay

Reputation: 514

How to import module in nodejs from some external file

I have this file indexjs where I am exporting data

exports.updateMobileNumber = updateMobileNumber;

and in my appjs I am importing it.

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

Now another file mainjs is on external URL like

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

How to import this file in my appjs

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. 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?

Upvotes: 0

Views: 1325

Answers (2)

Marc
Marc

Reputation: 2859

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.

--

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!

    more about http inside node:

  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. (keywords: npm, modularization, vendors, helpers)

Upvotes: 2

Defiant
Defiant

Reputation: 156

NPM is designed for you to install and manage remote modules. Modules must be locally accessible and installed when a NodeJS instance is started up.

If you require a module not known to your package.json file, an error will be thrown.

Edit: require is synchronous, so it can't load non-local files (which would be an asynchronous operation). You could load data asynchronously though, using request.

Upvotes: 2

Related Questions