2017-04-21 121 views

回答

1

Express是圍繞由nodejs核心模塊提供的原始Http模塊構建的。看看該文檔約http.createServer

因爲每個reqres在requestListener是一個流,你其實可以與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! 

希望這有助於!