稳定性: 0 - 弃用: 改为使用 [fs.stat()] 或 [fs.access()]。

    • path {string|Buffer|URL}
    • callback {Function}
      • exists {boolean}

    通过检查文件系统来测试给定的路径是否存在。 然后调用 callback 并带上参数 truefalse

    1. fs.exists('/etc/passwd', (exists) => {
    2. console.log(exists ? '存在' : '不存在');
    3. });

    此回调的参数与其他 Node.js 回调不一致。 通常,Node.js 回调的第一个参数是 err 参数,后面可选地跟随其他参数。 fs.exists() 的回调只有一个布尔值参数。 这是推荐 fs.access() 代替 fs.exists() 的原因之一。

    不建议在调用 fs.open()fs.readFile()fs.writeFile() 之前使用 fs.exists() 检查文件是否存在。 这样做会引入竞态条件,因为其他进程可能会在两次调用之间更改文件的状态。 相反,应该直接打开、读取或写入文件,如果文件不存在则处理引发的错误。

    写入(不推荐)

    1. fs.exists('myfile', (exists) => {
    2. if (exists) {
    3. console.error('myfile 已存在');
    4. } else {
    5. fs.open('myfile', 'wx', (err, fd) => {
    6. if (err) throw err;
    7. writeMyData(fd);
    8. });
    9. }
    10. });

    写入(推荐)

    1. fs.open('myfile', 'wx', (err, fd) => {
    2. if (err) {
    3. if (err.code === 'EEXIST') {
    4. console.error('myfile 已存在');
    5. return;
    6. }
    7. throw err;
    8. }
    9. writeMyData(fd);
    10. });

    读取(不推荐)

    1. fs.exists('myfile', (exists) => {
    2. if (exists) {
    3. fs.open('myfile', 'r', (err, fd) => {
    4. if (err) throw err;
    5. readMyData(fd);
    6. });
    7. } else {
    8. console.error('myfile 不存在');
    9. }
    10. });

    读取(推荐)

    1. fs.open('myfile', 'r', (err, fd) => {
    2. if (err) {
    3. if (err.code === 'ENOENT') {
    4. console.error('myfile 不存在');
    5. return;
    6. }
    7. throw err;
    8. }
    9. readMyData(fd);
    10. });

    上面的“不推荐”示例会先检查文件是否存在然后再使用该文件。 “推荐”示例则更好,因为它们直接使用文件并处理错误(如果有错误的话)。

    通常,仅在文件不直接使用时才检查文件是否存在,例如当其存在性是来自另一个进程的信号时。