Skip to content

Commit 6108ea9

Browse files
yorkieFishrock123
authored andcommitted
fs: consider NaN/Infinity in toUnixTimestamp
PR-URL: #2387 Reviewed-By: Trevor Norris <[email protected]>
1 parent ea15d71 commit 6108ea9

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

doc/api/fs.markdown

+8
Original file line numberDiff line numberDiff line change
@@ -363,6 +363,14 @@ descriptor.
363363

364364
Change file timestamps of the file referenced by the supplied path.
365365

366+
Note: the arguments `atime` and `mtime` of the following related functions does
367+
follow the below rules:
368+
369+
- If the value is a numberable string like "123456789", the value would get
370+
converted to corresponding number.
371+
- If the value is `NaN` or `Infinity`, the value would get converted to
372+
`Date.now()`.
373+
366374
## fs.utimesSync(path, atime, mtime)
367375

368376
Synchronous version of `fs.utimes()`. Returns `undefined`.

lib/fs.js

+6
Original file line numberDiff line numberDiff line change
@@ -1045,7 +1045,13 @@ fs.chownSync = function(path, uid, gid) {
10451045

10461046
// converts Date or number to a fractional UNIX timestamp
10471047
function toUnixTimestamp(time) {
1048+
if (typeof time === 'string' && +time == time) {
1049+
return +time;
1050+
}
10481051
if (typeof time === 'number') {
1052+
if (!Number.isFinite(time) || time < 0) {
1053+
return Date.now() / 1000;
1054+
}
10491055
return time;
10501056
}
10511057
if (util.isDate(time)) {

test/parallel/test-fs-utimes.js

+7-1
Original file line numberDiff line numberDiff line change
@@ -122,16 +122,22 @@ function runTest(atime, mtime, callback) {
122122

123123
var stats = fs.statSync(__filename);
124124

125+
// run tests
125126
runTest(new Date('1982-09-10 13:37'), new Date('1982-09-10 13:37'), function() {
126127
runTest(new Date(), new Date(), function() {
127128
runTest(123456.789, 123456.789, function() {
128129
runTest(stats.mtime, stats.mtime, function() {
129-
// done
130+
runTest(NaN, Infinity, function() {
131+
runTest('123456', -1, function() {
132+
// done
133+
});
134+
});
130135
});
131136
});
132137
});
133138
});
134139

140+
135141
process.on('exit', function() {
136142
console.log('Tests run / ok:', tests_run, '/', tests_ok);
137143
assert.equal(tests_ok, tests_run);

0 commit comments

Comments
 (0)