Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue #654 working on adding feature fs.watchFile() #748

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,7 @@ const fs = new Filer.FileSystem(options, callback);
* [fs.removexattr(path, name, callback)](#removexattr)
* [fs.fremovexattr(fd, name, callback)](#fremovexattr)
* [fs.watch(filename, [options], [listener])](#watch)
* [fs.watchFile(filename, [options], [listener])](#watchFile)

#### fs.rename(oldPath, newPath, callback)<a name="rename"></a>

Expand Down Expand Up @@ -1323,6 +1324,24 @@ var watcher = fs.watch('/data', { recursive: true }, function(event, filename) {
fs.writeFile('/data/subdir/file', 'data');
```

### fs.watchFile(filename, [options], [listener])<a name="watch"></a>

Watch for changes on a file at `filename`. The callback `listener` will be called each time the file is accessed.

The `options` argument only supports the change in interval between checks measured in milliseconds and does not support perstistence like node.

The `listener` receives two arguments that are the current stat object and previous stat object that are instances of `fs.Stat`. Reference to `fs.Stat` can be found
here: [`fs.Stat`](https://nodejs.org/api/fs.html#fs_class_fs_stats)

Example:
```javascript
fs.watchFile('/myfile.txt', (curr, prev) => {
console.log(`the current mtime is: ${curr.mtime}`);
console.log(`the previous mtime was: ${prev.mtime}`);
});
```


### FileSystemShell<a name="FileSystemShell"></a>

Many common file system shell operations are available by using a `FileSystemShell` object.
Expand Down
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

54 changes: 54 additions & 0 deletions src/filesystem/interface.js
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,60 @@ function FileSystem(options, callback) {
return watcher;
};

//Object that uses filenames as keys
const statWatchers = new Map();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry to flip back and forth on this, but I'm not clear what benefit we're gaining from Map here over {} for potential loss in compatibility. Can we switch back to {} instead?


this.watchFile = function (filename, options, listener) {
let prevStat, currStat;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should probably call Path.normalize(filename) on filename before we use it internally.


if (Path.isNull(filename)) {
throw new Error('Path must be a string without null bytes.');
}
// Checks to see if there were options passed in and if not, the callback function will be set here
if (typeof options === 'function') {
listener = options;
options = {};
}
// default 5007ms interval, persistent is not used this project
const interval = options.interval || 5007;
listener = listener || nop;

let intervalValue = statWatchers.get(filename);

if(intervalValue) {
return;
}
else {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No else after return. Get rid of this and unindent the code below.

fs.stat(filename, function (err, stats) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's some kind of timing bug here. You do a stat, and then inside the callback you start your interval, but never seem to call stat again in that interval's callback. Each interval should recall stat, so you have updated values for prev/currStat.

Also, this raises the question about the interval's lower bounds. There is some amount of time that a stat will take to execute. We shouldn't trigger another one before it's done. Probably we should ignore requests for interval to be lower than 5007 and just use that as our floor.

var value = setInterval(function () {
prevStat = currStat;

//Conditional check for first run to set initial state for prevStat
if(!prevStat) {
prevStat = stats;
}

currStat = stats;

if (err) {
clearInterval(value);
console.warn('[Filer Error] fs.watchFile encountered an error' + err.message);
}
if (JSON.stringify(prevStat) !== JSON.stringify(currStat)) {
listener(prevStat, currStat);
}
// Set a new prevStat based on previous
prevStat = currStat;
},
interval
);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indents here seem wrong, these 3 lines shouldn't all line up.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought so too, but I checked the spacings and it looked right, also the linting will fail if I change it.


// Stores interval return values
statWatchers.set(filename, value);
});
}
};

// Deal with various approaches to node ID creation
function wrappedGuidFn(context) {
return function (callback) {
Expand Down
1 change: 1 addition & 0 deletions tests/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ require('./spec/trailing-slashes.spec');
require('./spec/times.spec');
require('./spec/time-flags.spec');
require('./spec/fs.watch.spec');
require('./spec/fs.watchFile.spec');
require('./spec/fs.unwatchFile.spec');
require('./spec/errors.spec');
require('./spec/fs.shell.spec');
Expand Down
69 changes: 69 additions & 0 deletions tests/spec/fs.watchFile.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
'use strict';

var util = require('../lib/test-utils.js');
var expect = require('chai').expect;

describe('fs.watchFile', function() {
beforeEach(util.setup);
afterEach(util.cleanup);

it('should be a function', function() {
const fs = util.fs();
expect(typeof fs.watchFile).to.equal('function');
});

it('should throw an error if a file path is not defined', function() {
const fs = util.fs();

const fn = () => fs.watchFile(undefined);
expect(fn).to.throw();
});

it('should throw an error if a file is deleted', function() {
const fs = util.fs();

fs.writeFile('/myfile', 'data', function(error) {
if(error) throw error;
});

fs.watchFile('/myfile', function(prev, curr) {
expect(prev).to.exist;
expect(curr).to.exist;
});

fs.unlink('/myfile');

const fn = () => fs.watchFile('/myfile');
expect(fn).to.throw();
});

it('prev and curr should be equal if nothing has been changed in the file', function() {
const fs = util.fs();

fs.writeFile('/myfile', 'data', function(error) {
if(error) throw error;
});

fs.watchFile('/myfile', function(prev, curr) {
expect(prev).to.equal(curr);
});
});

it('prev and curr should not be equal if something has been changed in the file', function() {
const fs = util.fs();

fs.writeFile('/myfile', 'data', function(error) {
if(error) throw error;
});

fs.watchFile('/myfile', function(prev, curr) {
expect(prev).to.equal(curr);

fs.writeFile('/myfile', 'data2', function(error) {
if(error) throw error;
});

expect(prev).to.not.equal(curr);
});
});
});