Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js get open file descriptor count (development)

Tags:

node.js

I'm using chokidar to watch files, and I get EMFILE errors, and I know that this happened because I have too many file descriptors currently open.

I'm using socket, so graceful-fs doesn't fix the problem. Also, setting my ulimit temporarily is, well, temporary.

Is there a way to get the number of file descriptors currently open in code? I want to check if the number is about to go over limit, and make the process wait before it continues watching files/directories.

like image 681
user3467433 Avatar asked Jul 01 '15 02:07

user3467433


People also ask

How do you get the count of open file descriptors for a process?

How can I take the open files count for each process in Linux? if you're running it from root (e.g. prefixing the command with sudo -E env PATH=$PATH ), otherwise it'll only return file descriptor counts per process whose /proc/{pid}/fd you may list.

How do you know how many file descriptors?

You can read /proc/sys/fs/file-nr to find the total number of allocated and free file system handles as well as the maximum allowed.

How many open file descriptors does each process have by default?

A process has three file descriptors open by default, denoted by 0 for stdin, 1 for stdout, and 2 for stderr.

How many file descriptors can I open?

Linux systems limit the number of file descriptors that any one process may open to 1024 per process. (This condition is not a problem on Solaris machines, x86, x64, or SPARC). After the directory server has exceeded the file descriptor limit of 1024 per process, any new process and worker threads will be blocked.


1 Answers

A simple way to get the current open fd count (assuming you have a /proc fs) is to check the number of entries in /proc/self/fd:

var readdir = require('fs').readdir;

readdir('/proc/self/fd', function(err, list) {
  if (err) throw err;
  console.log(list.length);
});

Keep in mind, opening the directory for reading will incur another open fd.

If you want to check the number of open file descriptors from an external process, just replace self with the pid you want to check.

like image 161
mscdex Avatar answered Oct 02 '22 07:10

mscdex