U
U
urgjfvuirakjkd2019-01-29 00:30:03
Node.js
urgjfvuirakjkd, 2019-01-29 00:30:03

How to make a multi-threaded HTTP(S) server in a node?

On the node, I need to write a web server that, when opened at 127.0.0.1:8080, will drag files in the background via wget and give them back.
Here is a simple server example

var http = require('http');
http.createServer(function (req, res) {
//тут 60 секунд идет работа в СИНХРОННОМ режиме через wget и подобные
//fs.readFileSync
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(req.url);
    res.end();
}).listen(8080);

I open 2 different browsers
In each I drive 127.0.0.1:8080 and press Enter at the same time
And oops!
One browser works, then as the first finishes work, the second one starts working.
No multithreading i.e. the second waits until the first finishes work.
I did not expect this from a node.
What is the problem? and how to test the web server for asynchrony and how to make it possible to connect to 100 threads at this address 127.0.0.1:8080?
Can't get rid of fs.readFileSync

Answer the question

In order to leave comments, you need to log in

5 answer(s)
D
DevMan, 2019-01-29
@urgjfvuirakjkd

The node has never been multi-threaded out of the box.
A long operation (image conversion) blocks the server, what should I do?

D
Developer, 2019-01-29
@samodum

You need to change the node to Go

K
Kirill Kudryavtsev, 2019-01-29
@Deissh

There are no such situations when fs.readFileSync cannot be got rid of, the problem is already in the developer who is trying to get rid of it.
Your whole problem is in synchronous fs.readFileSync.

O
ofigenn, 2019-01-30
@ofigenn

It's not clear from the code what the problem is. By itself, a synchronous file read only blocks the thread for the duration of the read. Large files? how much memory is on the server?
But sending the buffer will go asynchronously. And in this case it is strange that the second request is executed strictly after the first one.
Ideally, of course, use fs.createReadStream. Then there will be no problems with either memory or locks.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question