Reputation: 1824
What is the best way to save uploaded to node.js files without express?
Upvotes: 0
Views: 1010
Reputation: 1957
Express is built around the raw Http module provided by the nodejs core module. Take a look at the docs about http.createServer
Because each req
and res
in the requestListener is a stream, you can actually do this quite easily with the fs
core module.
var http = require('http');
var fs = require('fs');
var server = http.createServer(function requestListener (req, res) {
req.once('end', function onEnd () {
res.statusCode = 200;
res.end('Uploaded File\n');
});
req.pipe(fs.createWriteStream('./uploadedFile.txt'));
});
server.listen(8080);
Try uploading the file:
# file contains "hello world!"
curl -v -d @test.txt localhost:8080
* Rebuilt URL to: localhost:8080/
* Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> POST / HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.51.0
> Accept: */*
> Content-Length: 12
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 12 out of 12 bytes
< HTTP/1.1 200 OK
< Date: Fri, 21 Apr 2017 01:34:21 GMT
< Connection: keep-alive
< Content-Length: 14
<
Uploaded File
* Curl_http_done: called premature == 0
* Connection #0 to host localhost left intact
and check out the file
cat uploadedFile.txt
hello world!
Hope this helps!
Upvotes: 1