wazzaday
wazzaday

Reputation: 9664

Can I run multiple node.js files

I have a server.js file which runs my server and displays html files. In a client side javascript file I would like to make an ajax request to a separate server side js file which pulls in data from an API. Is this possible? or is there a better solution when working in a node environment.

Upvotes: 1

Views: 2574

Answers (1)

alandarev
alandarev

Reputation: 8635

You can run multiple node.js files on a same server. Launching each with node my_file.js.


And yes, there is a better option to reach desired effect, instead of launching multiple servers. I would even discourage you launching second server, unless you intentionally want it to be fully independent entity.

Solution is called routing, for instance you want to serve two functionalities with Node.js:

  1. http://my-app.com/
  2. http://my-app.com/api/users

As I understand you know how to implement them, now you just need a router to unite them.

There are many routers available, with great examples and documentation.

Let us consider you have chosen Express, then following this guide your main (starting point) JS file will have simple instructions telling what JS file serves what part of your website:

app.get('/', mySite.index);
app.all('/api/*', myApi.index);

Notice: that is incomplete code, refer to ExpressJS documentation, or other router you decide to use. ExpressJS is a rich framework, if you need only router, you might want to find something simpler.

Upvotes: 2

Related Questions