5
我試圖upoad和下載圖像通過Node.js的服務器,我使用下面的代碼:錯誤:ENOENT,沒有這樣的文件或目錄節點JS
var http = require('http'),
path = require('path'),
os = require('os'),
fs= require('fs'),url = require('url');
var Busboy = require('busboy');
http.createServer(function(req, res) {
if (req.method === 'POST') {
var busboy = new Busboy({ headers: req.headers });
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
var saveTo = ".\\Images\\"+filename;
file.pipe(fs.createWriteStream(saveTo));
});
busboy.on('finish', function() {
res.writeHead(200, { 'Connection': 'close' });
res.end("That's all folks!");
});
return req.pipe(busboy);
}
else{
var request = url.parse(req.url, true);
console.log(request);
var action = request.pathname;
console.log(action);
if (action !== '/') {
var img = fs.readFileSync('.'+action);
res.writeHead(200, {'Content-Type': 'image/gif' });
res.end(img, 'binary');
} else {
res.writeHead(200, {'Content-Type': 'text/plain' });
res.end('Hello World \n');
}
}
res.writeHead(404);
res.end();
}).listen(8082, function() {
console.log('Listening for requests');
});
當我試圖讓使用HTTP GET在http://localhost:8082/images/betty.jpg
這個服務器映像,請求得到滿足,圖像被收到,但它也將引發以下錯誤:
^
fs.js:438
return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
^
Error: ENOENT, no such file or directory 'D:\ImageUploadService\favicon.ico'
at Object.fs.openSync (fs.js:438:18)
at Object.fs.readFileSync (fs.js:289:15)
at Server.<anonymous> (D:\ImageUploadService\service.js:27:20)
at Server.emit (events.js:98:17)
at HTTPParser.parser.onIncoming (http.js:2112:12)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:121:23
)
at Socket.socket.ondata (http.js:1970:22)
at TCP.onread (net.js:527:27) 'D:\ImageUploadService\favicon.ico'
at Object.fs.openSync (fs.js:438:18)
at Object.fs.readFileSync (fs.js:289:15)
at Server.<anonymous> (D:\ImageUploadService\service.js:27:20)
at Server.emit (events.js:98:17)
at HTTPParser.parser.onIncoming (http.js:2112:12)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:121:23
)
at Socket.socket.ondata (http.js:1970:22)
at TCP.onread (net.js:527:27)
它似乎是在尋找一些favicon.ico的。可能是什麼問題呢??
僅供參考,這是有點反模式,而不是一個好習慣是在它的好得多而已。捕獲'fs.readFileSync()'上的錯誤,並安全地處理ENOENT錯誤,因爲這在多任務世界中效果更好。最好不要在覈心事件處理中使用同步文件I/O。 – jfriend00 2014-09-27 01:57:35
要小心,'存在'將嚴重廢棄由jfriend00提及的原因,並且不適用於fs的其他版本。 – 2015-06-15 17:33:08
Webpack和節點新手在這裏。花費2天試圖弄清楚這一點。 「存在」可能會被棄用,這可能是一個壞習慣,但我必須明天提供工作流程設置,我真的需要這個。謝謝。 – Larrydx 2016-05-22 17:04:20