Roman Nazarkin
Roman Nazarkin

Reputation: 2229

Client-side Javascript server - possible?

Great day, community.

Question is next: is that possible to run simple HTTP server on client-side javascript which will be able to receive requests from global network and somehow process them?

For example, in a node.js I can run server with following code:

var http = require('http');
http.createServer().listen(3000, '127.0.0.1');

and then I'll have server running on 127.0.0.1:3000, I'm wonder to know is something similar to this can be implemented with a regular client-side javascript?

Upvotes: 5

Views: 2270

Answers (1)

FeifanZ
FeifanZ

Reputation: 16316

The definitions of "client" and "server" are relative. Node can be a server when it's sending data to clients; a Node app can also be a client to another server (for example, when you make an API call).

It sounds like you're asking if you can create a "server" using JS in the browser. You can't, but that's because most browsers are designed to only be clients, not servers — they can only make requests, not respond to them. In particular, Node itself connects to system-level sockets, which enable it to be a server. Browsers don't allow your Javascript code access to those system-level sockets, which is why it isn't possible.

Hypothetically, if they did, then you'd end up back at Node. Or recreating your own version of Node.

Note that you do have WebSockets in the browser; any other "client" can be on the "other side" of that socket. So you could implement a rudimentary client/server setup that way, but it wouldn't work with other HTTP clients.

Upvotes: 4

Related Questions