diff --git a/doc/api/fs.md b/doc/api/fs.md index 32994108f21701..0668f1e24f3cd5 100644 --- a/doc/api/fs.md +++ b/doc/api/fs.md @@ -300,6 +300,93 @@ fs.access('/etc/passwd', fs.R_OK | fs.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])