Skip to content

Commit

Permalink
first import
Browse files Browse the repository at this point in the history
  • Loading branch information
kerphi committed Jul 6, 2013
0 parents commit c5fb85d
Show file tree
Hide file tree
Showing 6 changed files with 259 additions and 0 deletions.
22 changes: 22 additions & 0 deletions LICENSE
@@ -0,0 +1,22 @@
(The MIT License)

Copyright (c) 2013 Stéphane Gully <stephane.gully@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
43 changes: 43 additions & 0 deletions README.md
@@ -0,0 +1,43 @@
# node-inotifywait

Yet another nodejs fs.watch implementation that can watch:

* folders recursively
* big number of directories and files
* with low CPU use

This implementation is a wrapper above the inotifywait system command.

### Why

Because other implementations:
* [fs.watch](http://nodejs.org/api/fs.html)
* [node-watch](https://github.com/yuanchuan/node-watch)
* [chokidar](https://github.com/paulmillr/chokidar)
* [watch](https://github.com/mikeal/watch)

Are not performant for huge number of directories and files watching. Some are not recursive, other have high CPU usage when watching lot of directories and files.

### Installation

```bash
npm install inotifywait
```

### Example

```js
var inw = require('inotifywait');

var watch1 = inw.watch('/tmp/', { recursive: false });
watch1.on('add', function (filename) {
console.log(filename + ' added');
watch1.close(); // stop watching
});

var watch2 = inw.watch('/var/log/', { recursive: true });
watch2.on('change', function (filename) {
console.log(filename + ' changed');
watch2.close(); // stop watching
});
```
1 change: 1 addition & 0 deletions index.js
@@ -0,0 +1 @@
module.exports = require('./lib/inotifywait');
103 changes: 103 additions & 0 deletions lib/inotifywait.js
@@ -0,0 +1,103 @@
/*jslint node: true, maxlen: 100, maxerr: 50, indent: 2 */
'use strict';

var fs = require('fs');
var util = require('util');
var spawn = require('child_process').spawn;
var Lazy = require('lazy');
var EventEmitter = require('events').EventEmitter;

module.exports.watch = function (wpath, options) {
options = mixin({
recursive: true,
watchDirectory: false
}, options);

var ee = new EventEmitter();
var currentEvents = {};

// run inotifywait command in background
var inwp = spawn('inotifywait', [
(options.recursive ? '-r' : ''),
'--format',
'{ "type": "%e", "file": "%w%f" }',
'-m',
'-q',
wpath
]);

// parse stdout of the inotifywatch command
Lazy(inwp.stdout)
.lines
.map(String)
.map(function (line) {
try {
return JSON.parse(line);
} catch (err) {
return { type: '', file: '' };
}
})
.map(function (event) {
event.type = event.type.split(',');
return event;
})
.forEach(function (event) {
//console.log(event);

// skip directories ?
var isDir = (event.type.indexOf('ISDIR') != -1);
if (isDir && !options.watchDirectory) {
return;
}

if (event.type.indexOf('CREATE') != -1) {
currentEvents[event.file] = 'add';
} else if (event.type.indexOf('MODIFY') != -1) {
if (currentEvents[event.file] != 'add') {
currentEvents[event.file] = 'change';
}
} else if (event.type.indexOf('DELETE') != -1) {
ee.emit('unlink', event.file);
} else if (event.type.indexOf('CLOSE') != -1) {
if (currentEvents[event.file]) {
ee.emit(currentEvents[event.file], event.file);
delete currentEvents[event.file];
} else {
ee.emit('unknown', event.file);
}
}
});

inwp.stderr.on('data', function (data) {
ee.emit('error', new Error(data.toString()));
});

/**
* Function used to stop the watch
*/
ee.close = function (cb) {
inwp.on('close', function (err) {
if (cb) {
cb(code);
}
});
inwp.kill();
}

return ee;
};

/**
* Mixing object properties.
*/
var mixin = function() {
var mix = {};
[].forEach.call(arguments, function(arg) {
for (var name in arg) {
if (arg.hasOwnProperty(name)) {
mix[name] = arg[name];
}
}
});
return mix;
};
21 changes: 21 additions & 0 deletions package.json
@@ -0,0 +1,21 @@
{
"name": "inotifywait",
"version": "0.0.1",
"description": "Yet another nodejs fs.watch/inotify implementation. Good for big directories structures and lot of files.",
"main": "index.js",
"scripts": {
"test": "mocha"
},
"author": "Stéphane Gully <stephane.gully@gmail.com>",
"license": "BSD",
"devDependencies": {
"mocha": "~1.12.0",
"chai": "~1.7.2",
"uuid": "~1.4.1",
"mkdirp": "~0.3.5",
"remove": "~0.1.5"
},
"dependencies": {
"lazy": "~1.0.11"
}
}
69 changes: 69 additions & 0 deletions test/inotifywait.js
@@ -0,0 +1,69 @@
var expect = require('chai').expect;
var iws = require('../index.js');
var uuid = require('uuid');
var fs = require('fs');
var mkdirp = require('mkdirp');
var remove = require('remove');

var fakeFile = '';
before(function(){
fakeFile = generateFakeFile('fake1');
});

describe('inotifywait', function () {
describe('.watch()', function () {
it('should detect when a new file is added', function (done) {
var f = '';
setTimeout(function () {
f = generateFakeFile('fake2');
}, 10);
var w = iws.watch(__dirname + '/data');
w.on('add', function (filename) {
expect(filename).to.eql(f);
w.close();
done();
});
});

it('should detect when a file is modified', function (done) {
setTimeout(function () {
fs.writeFileSync(fakeFile, '...');
}, 10);
var w = iws.watch(__dirname + '/data');
w.on('change', function (filename) {
expect(filename).to.eql(fakeFile);
w.close();
done();
});
})

it('should detect when a file is removed', function (done) {
setTimeout(function () {
remove.removeSync(fakeFile);
}, 10);
var w = iws.watch(__dirname + '/data');
w.on('unlink', function (filename) {
expect(filename).to.eql(fakeFile);
w.close();
done();
});
})

})
});

after(function(){
remove.removeSync(__dirname + '/data');
});

function generateFakeFile(name) {
//var id = uuid.v4();
var path = __dirname + '/data'; // + id[0] + '/' + id[1] + '/' + id[2];
var file = path + '/' + name;

mkdirp.sync(path);
//console.log(path + ' created [' + i + ']');
fs.writeFileSync(file, '.');
//console.log(file + ' created [' + i + ']');
return file;
}

0 comments on commit c5fb85d

Please sign in to comment.