Node.js | fs.existsSync () Метод

Опубликовано: 4 Августа, 2021

Метод fs.existsSync () используется для синхронной проверки, существует ли уже файл по заданному пути или нет. Он возвращает логическое значение, которое указывает на наличие файла.

Синтаксис:

 fs.existsSync (путь)

Параметры: этот метод принимает один параметр, как указано выше и описано ниже:

  • path: содержит путь к файлу, который необходимо проверить. Это может быть строка, буфер или URL.

Возвращаемое значение: возвращает логическое значение, т.е. истина, если файл существует, в противном случае возвращает ложь .

Ниже программы иллюстрируют метод fs.existsSync () в Node.js:

Пример 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( " Current filenames:" );
fs.readdirSync(__dirname).forEach(file => {
console.log(file);
});
console.log( " " );
}

Выход:

Текущие имена файлов:
hello.txt
index.js
package.json


hello.txt существует: true
world.txt существует: 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( " Current filenames:" );
fs.readdirSync(__dirname).forEach(file => {
console.log(file);
});
console.log( " " );
}

Выход:

Текущие имена файлов:
hello.txt
index.js
package.json


hello.txt существует: true

Текущие имена файлов:
hello.txt
index.js
package.json


hello.txt существует: true

Ссылка: https://nodejs.org/api/fs.html#fs_fs_existssync_path