XMLHttpRequest progressive download? - javascript

Just for fun I was creating a JavaScript console for controlling my PC. It involves a small webserver that takes command strings and forwards those to the system using popen calls (to be more specific popen4 on a Ruby mongrel server). The stdout channels are redirected to the http response.
The problem is that the response only arrives once the entire contents of stdout has been sent. This is ok for small commands, but not for a command like find / which lists all the files in the system. In such situations it would be nice to have the results shown progressively in the webview (just like in the regular terminal).
I thought that using XMLHttpRequest synchronously might result in progressive downloading, but it doesn't seem so.
Is there any way to make it work?

Quick question, are you flushing the response stream? If not the the request will wait until it has been. Just a thought as this is the case when creating progressive download of files etc

Related

How to use pdfkit npm in async manner

I have written an application in node.js which takes input from user and generates pdfs file based on few templates.
I am using pdfkit npm for this purpose. My application is running in production. But my application is very slow, below are the reasons :
What problem I am facing :
It is working in sync manner. I can explain it by giving an example- Suppose a request come to the application to generate a pdf, is starts processing and after processing it returns back the response with generated pdf url. But if multiple request comes to the server it process each request one by one(in sync manner).
All request in queue have to wait untill the previous one is finished.
Maximum time my application gives Timeout or Internal Server Error.
I can not change the library, why ?
There are 40 templates I have written in js for pdfkit. And each template is of 1000 - 3000 lines.
If I will change the lib, i have to rewrite those templates according to new library.
It will take many months to rewrite and test it properly.
What solution I am using now :
I am managing a queue now, once a request come it got queued and a satisfactory message send back in response to the user.
Why this solution is not feasible ?
User should be provided valid pdf url upon success of request. But in queue approach, user is getting only a confirmation message. And pdf is being processed later in queue.
What kind of solution I am seeking now ?
Any way through which I can make this application multi-threaded/asynchronous, So that it will be capable of handling multiple request on a time without blocking the resource?
Please save my life.
I hate to break it to you, but doing computation in the order tasks come in is a pretty fundamental part of node. It sounds like loading these templates is a CPU-bound task, and since Node is single-threaded, it knocks these off the queue in the order they come in.
On the other hand, any framework would have a similar problem. Node being single-threading means its actually very efficient, because it doesn't lose cycles to context switching.
How many PDF-generations can your program handle at once? What type of hardware are you running this on? If it's failing on a few requests a second, then there's probably a programming fix.
For node, the more things you can make asynchronous the better. For example, any time you're reading a file in, it should be asynchronous.
Can you post the code for one of your PDF-creating request functions?

Integrate Node.js with Symfony2 or PHP

I'm developing a web application with Symfony2. I need to create a push notifications sysmte (like Facebook). When an user publish something, I need some of another users receive a notification.
I saw that Node.js it's the easiest manner to do this. But, I did some simple examples and all works fine, but I don't know how can I integrate this node.js application with my Symfony2 application, or really with a PHP application.
Anybody can help me?
Thanks in advance!
Please note that you've not given enough details, so I will respond as a front-end developer and not as a mobile developer
Integrating NodeJS and PHP (in general) is not a good way since you need to launch both servers separatly, create the websocket server in JS while your application is in PHP and finally create a request (GET or POST) from your PHP to you JS server. Well, a big mess, so I'll expose my solution here under.
Quick insight for mobile apps. Well, technically, there's no easy way. You can use the Push "protocol" (http://www.wikiwand.com/en/Push_technology) with NotificationPusher (https://github.com/Ph3nol/NotificationPusher). I didn't used it before so I can't help you with it.
In general.
Most of the time when people thinks of Push, long polling will do the trick. For starters it means that the request is made client-side and the server don't send data & close connection until there's new data.
How do you implement this ?!?
Basically, you change the max_execution_time using ini_set or set_time_limit to a very long time for the current script and launch a loop (like a do..while) with a sleep and the check to your data inside. From your Javascript just make an Ajax call, for example with jquery: $.get. Just remember to remove the timeout and stay in asynchronous mode.
The only drawback of this solution is that you will always have a connection opened to your server which will consume a bit more of battery on a mobile device. If you have multiple types of data to receive do not hesitate to merge the calls and publish a type in your response data, since most of the browsers allows only 2 or 3 simultaneous connections to the same server.
I sounds like your describing WebSockets.
Take a look at Socket.io, its a module for node.js.
Also there is a example at GitHub https://github.com/Automattic/socket.io/tree/master/examples/chat
Interesting files for you should be the index.js and the public/main.js.
You can see the example live at http://socket.io/demos/chat/

Using Python to communicate with JavaScript?

Is there a way to send data packets from an active Python script to a webpage currently running JavaScript?
The specific usage I'm looking for is to give the ability for the webpage, using JavaScript, to tell the Python script information about the current state of the webpage, then for the Python script to interpret that data and then send data back to the webpage, which the JavaScript then uses to decide which function to execute.
This is for a video game bot (legally), so it would need to happen in real time. I'm fairly proficient in Python and web requests, but I'm just getting into JavaScript, so hopefully a solution for this wouldn't be too complex in terms of Javascript.
EDIT: One way I was thinking to accomplish this would be to have Javascript write to a file that the Python script could also read and write to, but a quick google search says that JavaScript is very limited in terms of file I/O. Would there be a way to accomplish this?
For security reasons, javascript in a browser is usually restricted to only communicate with the site it was loaded from.
Given that, that's an AJAX call, a very standard thing to do.
You can make HTTP requests using the XMLHttpRequest API, which Jquery abstracts with $.ajax and $.get. You can also use the lower level Websockets network API:
https://developer.mozilla.org/en-US/docs/WebSockets
Note that the XMLHttpRequest API will only allow requests to the same server, OR requests that return an appropriate Access-Control-Allow-Origin header.
It sounds like the Javascript is only going to send information, not receive any. In that case, you're in luck. I'm guessing you are also running the Javascript and the Python on the same machine.
Run a Python webserver on the machine the browser is running on. Here's a simple example:
http://webpy.org/install
Once visiting http://127.0.0.1:8080/ in your browser gives the message Hello World!, you can start adding more addresses to your website, for example http://127.0.0.1:8080/report_data, http://127.0.0.1:8080/report_event etc.
Your Javascript can then make AJAX requests using jQuery.ajax or XMLHTTPRequest, to the address http://127.0.0.1:8080/report_data, and pass the information as GET parameters.

Node.js chat without Socket.IO

I just started learning Node.js and as I was learning about the fs.watchFile() method, I was wondering if a chat website could be efficiently built with it (and fs.writeFile()), against for example Socket.IO which is stable, but I believe not 100% stable (several fallbacks, including flash).
Using fs.watchFile could perhaps also be used to keep histories of the chats quite simply (as JSON would be used on the spot).
The chat files could be formatted in JSON in such a way that only the last chatter's message is brought up to the DOM (or whatever to make it efficient to 'fetch' messages when the file gets updated).
I haven't tried it yet as I still need to learn more about Node, and even more to be able to compare it with Socket.IO, but what's your opinion about it? Could it be an efficient/stable way of doing chats?
fs.watchFile() can be used to watch changes to the file in the local filesystem (on the server). This will not solve your need to update all clients chat messages in their browsers. You'll still need web sockets, AJAX or Flash for that (or socket.io, which handles all of those).
What you could typically do in the client is to try to use Web Sockets. If browser does not support them, try to use XMLHttpRequest. If that fails, fallback to Flash. It's a lot of programming to do, and it has to be handled by node.js server as well. Socket.io does that for you.
Also, socket.io is pretty stable. Fallback to Flash is not due to it's instability but due to lack of browser support for better solutions (like Web Sockets).
Storing chat files in flatfile JSON is not a good idea, because if you are going to manipulating the files, you would have to parse and serialize entire JSON objects, which would become very slow as the size of the JSON object increased. The watch methods for the filesystem module also don't work on all operating systems.
You also can't compare Node.js to Socket.IO because they are entirely different things. Socket.IO is a Node module for realtime transport between the browser and the server. What you need is dependent on what you're doing. If you need chat history, then you should be using a database such as MongoDB or MySQL. Watching files for changes is not an efficient way and you should just send messages as they received.
In conclusion no, using fs.watchFile() and fs.writeFile() is a very bad idea, because race conditions would occur due to concurrent file writes, besides that fs.watchFile() uses polling to check if a file has changed. You should instead use Socket.IO and push messages to other clients / store them in a database as they are received.
You can use long pooling method using javascript setTimeout and setInterval
long pooling
basically long pooling working on Ajax reqest and server responce time.
server will respond after a certain time (like after 50 seconds ) if there is not notification or message else it will respond with data and from client side when client gets response client javascript makes another request for new update and wait till response this process is endless until server is running

HTTP Body Streaming with Javascript

I am writing a debug/admin node server that allows users to execute a long-running process on the machine. I want to stream the output of the child process to the form they began the action from.
I can do this with sockets, but I have to have the client subscribe to a channel, and I have to post messages to the whole channel when they only have to do with the one client.
I'd prefer to be able to stream the http body down to the client. I can do this fairly easily with node: just keep writing to the request's socket, call end when I'm done.
Is there any way to use XhrHttpRequest to call a web service, have it fire events whenever new data is available, and a final event when it closes? Possible with jQuery?
Note that this isn't really the same use case as normal real-time updates, for which sockets are a good choice. This is a single request. I just want to get the response in pieces.
What I was hoping isn't possible: you can't make an xhr http request and keep it open, parsing chunks at a time.
Here is a summary of people's suggestions
Use socket.io anyway, and change your architecture to support pushing events.
Use socket.io, but make requests through it, as if you were hitting urls. Make a little url router on the server side of socket.io and stream stuff down all you want.
Keep the initial html page open and parse it as you go (not feasible for my implementation)
(3), but in a hidden iframe.
I went with 2.
As an update to this question, nowadays, you can use Sever-sent events (SSE). That way, you don't need to do anything particularly special on the server side, or setup websockets, which is overkill when you don't need full duplex. And XHR will keep the entire data in memory, which is non-ideal for large files. I had the same question, and I answered it here:
How to process streaming HTTP GET data?
some years ago i used "javascript" streaming over open http response. (years before ajax appeared)
the idea here : write chunks of
<script type="text/javascript">do js stuff here</script>
for each step of the process you want the client to react on.
it may still work.

Categories

Resources