From 143d38c650705dbd03aa09162bc3f5d15936d9ba Mon Sep 17 00:00:00 2001 From: Dan Fabulich Date: Fri, 22 Jul 2016 00:30:45 -0700 Subject: [PATCH] doc: bad/better examples for fs.access() and fs.exists() PR-URL: https://github.com/nodejs/node/pull/7832 Reviewed-By: James M Snell Reviewed-By: Anna Henningsen --- doc/api/fs.md | 169 ++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 164 insertions(+), 5 deletions(-) diff --git a/doc/api/fs.md b/doc/api/fs.md index e489125f763af6..2b9369ffa3b04c 100644 --- a/doc/api/fs.md +++ b/doc/api/fs.md @@ -347,6 +347,93 @@ fs.access('/etc/passwd', fs.constants.R_OK | fs.constants.W_OK, (err) => { }); ``` +Using `fs.access()` to check for the accessibility of a file before calling +`fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended. Doing +so introduces a race condition, since other processes may change the file's +state between the two calls. Instead, user code should open/read/write the +file directly and handle the error raised if the file is not accessible. + +For example: + + +**write (NOT RECOMMENDED)** + +```js +fs.access('myfile', (err) => { + if (!err) { + console.error('myfile already exists'); + return; + } + + fs.open('myfile', 'wx', (err, fd) => { + if (err) throw err; + writeMyData(fd); + }); +}); +``` + +**write (RECOMMENDED)** + +```js +fs.open('myfile', 'wx', (err, fd) => { + if (err) { + if (err.code === "EEXIST") { + console.error('myfile already exists'); + return; + } else { + throw err; + } + } + + writeMyData(fd); +}); +``` + +**read (NOT RECOMMENDED)** + +```js +fs.access('myfile', (err) => { + if (err) { + if (err.code === "ENOENT") { + console.error('myfile does not exist'); + return; + } else { + throw err; + } + } + + fs.open('myfile', 'r', (err, fd) => { + if (err) throw err; + readMyData(fd); + }); +}); +``` + +**read (RECOMMENDED)** + +```js +fs.open('myfile', 'r', (err, fd) => { + if (err) { + if (err.code === "ENOENT") { + console.error('myfile does not exist'); + return; + } else { + throw err; + } + } + + readMyData(fd); +}); +``` + +The "not recommended" examples above check for accessibility and then use the +file; the "recommended" examples are better because they use the file directly +and handle the error, if any. + +In general, check for the accessibility of a file only if the file won’t be +used directly, for example when its accessibility is a signal from another +process. + ## fs.accessSync(path[, mode])