Reputation: 3616
I build a server with node.js that use some require var.
For example, I have server.js
file with the next var: var s3 = require('s3')
In addition, server.js
contains some functions with callbacks. for example:
app.post('upload', function (req, res){
s3.upload(req.path);
}
app.post('delete', function (req, res){
s3.delete(req.path);
}
As I know, the application will run the request asynchronous.
My question is about s3: because I have only one s3 object (which defined by the require)- it will limit the asynchronous and concurrency of node.js. For example, the server get 10 requests from different clients. It can serve all, but it will limit by the s3 object which is common to all requests.
this is how node.js works? should I define collection of s3
objects?
Upvotes: 0
Views: 110
Reputation: 2040
Nodejs main (event) loop runs in a single thread.
Which means pretty much all code you write is executed one at the time. Nodejs' is asynchronic for 'slow' functions, like (but not limited to!) database calls or other IO operations such as file manipulation.
So only one upload and delete request is handled at a single time, ,and only one s3 object is needed./
Upvotes: 0
Reputation: 36777
No reason to define multiple s3 objects. Since node is effectively single threaded you won't gain anything from that - only one instruction will be executed at a time anyway.
Let's see how a hypothetical s3.method
is implemented (assuming here that s3 refers to amazon s3):
s3.method
s3.method
does some computation locally thens3.method
sends a request and awaits the response (or does some other form of input-output).1,2 and 4 are relatively fast operations compared to 3 (unless you do some heavy lifting in 1,2 or 4, but let's assume that's not the case).
So what node does when reaching operation 3 is yielding the control to some other part of your code while it's waiting for response. This waiting is handled by node runtime and OS-level event system. When the response arrives, it's handler is queued for execution and executed as soon as the control is yield back to node runtime and it's the first on the queue.
Upvotes: 1
Reputation: 1372
It's not necessary that s3 will wait for the action to finish: it's a common way in node.js to start running something and provide callback which will be called when the command finishes. Mainly it's designed so to optimize I/O actions and optimize for low CPU using applications.
Upvotes: 0