ns_write - Return data to client
These commands are used to manually construct and send an HTTP response piecewise (in a streaming manner), to the client.
Set the HTTP response status code and mime-type header for the data which is to be sent. The headers, including any extra headers set via the ns_conn outputheaders command, may not be flushed to the client until the first body data is written.
The -binary switch indicates that binary data is to be written, in which case the mime-type will be sent as given. Without this switch the mime-type will have the charset for the current connection's encoding appended. When length is specified, it will be set as content-length.
Returns 0.
Write all data directly to the client. No HTTP headers are sent unless ns_headers has been called.
If data is a Tcl byte-array object or the -binary option was given to ns_headers then no transcoding will take place. Otherwise, the encoding in effect for the current connection will be used to encode data.
If an HTTP response is being constructed (ns_headers has been called) and the client supports it, HTTP chunking will be used to stream data on each call to ns_write. If the client does not support HTTP chunking, connection keep-alive is disabled. Prefer to send a complete response using e.g. ns_return if possible.
ns_write returns true if all the data was written successfully and false otherwise. On failure, no more writes should be attempted.
After the command completes the connection remains open and available in the calling connection thread.
The command ns_writefp writes the contents of the specified file to the connection. One can specify the number of bytes to be copied in the nbytes argument. By default, the entire file is transmitted.
Report results progressively:
ns_register_proc GET /long-running-process { ns_headers 200 text/plain ns_write "Results: \n" while {[do_process result]} { ns_write "$result\n" } ns_write "Done." }
Sending binary data:
ns_register_proc GET /blobs { ... ns_headers -binary -- 200 application/x-whatever ns_write $blob1 $blob2 ... ns_write $blob3 }
Sending data to the connection from a file:
ns_register_proc GET /sampleWriteFp { ns_headers -- 200 text/plain set file [open "/usr/local/ns/copyright.txt" r] ns_writefp $file close $file }