6

I am trying to upoad and download images to the server via Node.js and I am using the below code:

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');
});

When I try to get the image from this server using HTTP GET at http://localhost:8082/images/betty.jpg, the request is fulfilled and the image is recieved but it also throws the error below:

             ^
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)

It seems that it is looking for some favicon.ico. What could be the problem??

writeToBhuwan
  • 3,233
  • 11
  • 39
  • 67

1 Answers1

8

You need to check if the file exists with fs.existsSync(path) before attempting to read it:

 if (action !== '/' && fs.existsSync('.'+action)) {
    var img = fs.readFileSync('.'+action);
    res.writeHead(200, {'Content-Type': 'image/gif' });
    res.end(img, 'binary');
 } else {
Dan D.
  • 73,243
  • 15
  • 104
  • 123
  • 5
    FYI, this is somewhat of an anti-pattern and not a good habit to be in. It's much better to just catch the error on `fs.readFileSync()` and safely handle an ENOENT error as this works better in a multi-tasking world. Also better not to be using synchronous file I/O in your core event handling either. – jfriend00 Sep 27 '14 at 01:57
  • 1
    Be careful, `exists` will seriously be deprecated for reasons mentioned by jfriend00 and won't work in further versions of fs. – Zachary Dahan Jun 15 '15 at 17:33
  • Webpack and Node newbie here. Spend 2 days trying to figure this out. "exists" may get deprecated and this may be a bad habit, but I have to deliver the workflow setup tomorrow and I really needed this. Thank you. – larrydalmeida May 22 '16 at 17:04
  • Weird. I personally always consider exceptions handling should be avoided every time it's possible (for example here when we can check if a file exists first) and use exceptions only for really unexpected cases, such as a network error, a disk operation failure, etc. – Benjamin Piette Oct 29 '20 at 03:00
  • Later, I wrote a better version of this: https://stackoverflow.com/questions/32322107/why-isnt-my-nodejs-web-server-fetching-files-from-my-directory/32322577#32322577 This was later extended to do if-modifed-since which required pausing the stream in the open event so that `fs.fstat` could be called before the stream started flowing. – Dan D. Oct 29 '20 at 13:58