TypeScript:
检查目录是否存在
如何操作:
当在Node.js环境中运行TypeScript时,你可以使用fs模块来检查目录是否存在,该模块提供了existsSync()函数或异步的access()函数结合constants.F_OK。
使用fs.existsSync():
import { existsSync } from 'fs';
const directoryPath = './path/to/directory';
if (existsSync(directoryPath)) {
console.log('目录存在。');
} else {
console.log('目录不存在。');
}使用fs.access()搭配fs.constants.F_OK:
import { access, constants } from 'fs';
const directoryPath = './path/to/directory';
access(directoryPath, constants.F_OK, (err) => {
if (err) {
console.log('目录不存在。');
return;
}
console.log('目录存在。');
});两种方法的示例输出,假设目录确实存在:
目录存在。如果不存在:
目录不存在。使用第三方库 - fs-extra:
fs-extra是一个受欢迎的第三方库,它增强了内置的fs模块,并提供了更方便的函数。
import { pathExists } from 'fs-extra';
const directoryPath = './path/to/directory';
pathExists(directoryPath).then(exists => {
console.log(`目录存在: ${exists}`);
});示例输出 当目录存在时:
目录存在: true如果不存在:
目录不存在: false