Skip to content

Instantly share code, notes, and snippets.

@panta82
Last active March 8, 2016 10:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save panta82/8bde4d1d6ec45394cc43 to your computer and use it in GitHub Desktop.
Save panta82/8bde4d1d6ec45394cc43 to your computer and use it in GitHub Desktop.
Get lsof information about a file (list of processes that are accessing that file)
var exec = require('child_process').exec,
util = require('util');
var target = process.argv[2];
if (!target) {
return usage(1);
}
var FIELDS = ['pid', 'command', 'uid', 'lock'];
var FIELD_OPTIONS = {
pid: { fn: Number },
command : {},
uid: { fn: Number },
lock: {}
};
lsofFile(target, function (err, results) {
if (err) {
console.error(err);
} else {
console.log(results);
}
});
function usage(exitCode) {
console.log(util.format('Usage: %s %s <target>', process.argv[0], process.argv[1]));
process.exit(exitCode >= 0 ? exitCode : 0);
}
function lsofFile(path, callback) {
exec('/usr/bin/lsof -F pucl -f -- ' + target, function (err, stdout, stderr) {
stderr = stderr ? stderr.toString() : '';
if (stderr && stderr.indexOf("No such file or directory") >= 0) {
err = new Error('File not found');
err.code = 'ENOENT';
err.errno = -2;
return callback(err);
}
if (err && err.code !== 1) {
return callback(new Error(stderr));
}
var results = [],
entryIndex = 0,
fieldIndex = 0;
stdout.split('\n').forEach(function (line) {
if (!line) {
return;
}
var field = FIELDS[fieldIndex];
var value = line.slice(1).trim();
if (FIELD_OPTIONS[field].fn) {
value = FIELD_OPTIONS[field].fn(value);
}
var entry = results[entryIndex] || (results[entryIndex] = {});
entry[field] = value;
fieldIndex++;
if (fieldIndex >= FIELDS.length) {
fieldIndex = 0;
entryIndex++;
}
});
return callback(null, results);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment