📜  Node.js fs.existsSync() 方法

📅  最后修改于: 2022-05-13 01:56:52.449000             🧑  作者: Mango

Node.js fs.existsSync() 方法

fs.existsSync() 方法用于同步检查给定路径中是否已存在文件。它返回一个布尔值,指示文件的存在。

句法:

fs.existsSync( path )

参数:此方法接受如上所述和如下所述的单个参数:

  • path:它保存必须检查的文件的路径。它可以是字符串、缓冲区或 URL。

返回值:它返回一个布尔值,即如果文件存在则返回true ,否则返回false

下面的程序说明了 Node.js 中的fs.existsSync() 方法

示例 1:

// Node.js program to demonstrate the
// fs.existsSync() method
  
// Import the filesystem module
const fs = require('fs');
  
// Get the current filenames
// in the directory
getCurrentFilenames();
  
let fileExists = fs.existsSync('hello.txt');
console.log("hello.txt exists:", fileExists);
  
fileExists = fs.existsSync('world.txt');
console.log("world.txt exists:", fileExists);
  
// Function to get current filenames
// in directory
function getCurrentFilenames() {
  console.log("\nCurrent filenames:");
  fs.readdirSync(__dirname).forEach(file => {
    console.log(file);
  });
  console.log("\n");
}

输出:

Current filenames:
hello.txt
index.js
package.json


hello.txt exists: true
world.txt exists: false

示例 2:

// Node.js program to demonstrate the
// fs.existsSync() method
  
// Import the filesystem module
const fs = require('fs');
  
// Get the current filenames
// in the directory
getCurrentFilenames();
  
// Check if the file exists
let fileExists = fs.existsSync('hello.txt');
console.log("hello.txt exists:", fileExists);
  
// If the file does not exist
// create it
if (!fileExists) {
  console.log("Creating the file")
  fs.writeFileSync("hello.txt", "Hello World");
}
  
// Get the current filenames
// in the directory
getCurrentFilenames();
  
// Check if the file exists again
fileExists = fs.existsSync('hello.txt');
console.log("hello.txt exists:", fileExists);
  
// Function to get current filenames
// in directory
function getCurrentFilenames() {
  console.log("\nCurrent filenames:");
  fs.readdirSync(__dirname).forEach(file => {
    console.log(file);
  });
  console.log("\n");
}

输出:

Current filenames:
hello.txt
index.js
package.json


hello.txt exists: true

Current filenames:
hello.txt
index.js
package.json


hello.txt exists: true

参考: https://nodejs.org/api/fs.html#fs_fs_existssync_path