在没有快递的情况下保存上传到node.js文件的最佳方法是什么?
答案 0 :(得分:1)
Express是围绕nodejs核心模块提供的原始Http模块构建的。请查看有关http.createServer
的文档因为requestListener中的每个req
和res
都是一个流,所以您可以使用fs
核心模块轻松地执行此操作。
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);
尝试上传文件:
# 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
并查看文件
cat uploadedFile.txt
hello world!
希望这有帮助!