Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error handling on readFileSync in node.js

I have this code

var fd = fs.openSync(filePath,"r");
var fr = fs.readSync(fd, buffer, 0, size, 0);

and it throws error like that

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: OK, open 'C:\Users\iahmed16\Desktop\eclipse WS\test\images\af31a9e0a98939be82f887b0005c21752e71425e.jpg'
  • how to handle this error ??
  • what's the meaning of the error if you know ??
like image 253
Islam Ahmed Avatar asked Aug 25 '13 10:08

Islam Ahmed


People also ask

Does readFileSync throw error?

readFileSync() method. And console-log the output. If the process fails, it throws an error object. The catch block receives the error object through the given parameter.

Which is better readFile or readFileSync?

In fs. readFile() method, we can read a file in a non-blocking asynchronous way, but in fs. readFileSync() method, we can read files in a synchronous way, i.e. we are telling node. js to block other parallel process and do the current file reading process.

How do you handle errors in Express?

The simplest way of handling errors in Express applications is by putting the error handling logic in the individual route handler functions. We can either check for specific error conditions or use a try-catch block for intercepting the error condition before invoking the logic for handling the error.


1 Answers

The error seems to mean that you have too many file descriptions open.

You have to make sure at some point that you close() them.

var fd = fs.openSync(filePath,"r");
var fr = fs.readSync(fd, buffer, 0, size, 0);
fs.closeSync(fd);

As for how to handle the error, you can use try...catch with thrown errors:

try {
    var fd = fs.openSync(filePath,"r");
    var fr = fs.readSync(fd, buffer, 0, size, 0);
    fs.closeSync(fd);
} catch (e) {
    console.log('Error:', e);
}
like image 123
Jonathan Lonowski Avatar answered Sep 27 '22 18:09

Jonathan Lonowski