主题
Node.js
目录
- 获取当前工作目录
js
console.log(process.cwd());- 获取当前文件所在目录
js
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
console.log(__dirname); // 当前文件所在目录文件
判断文件或目录是否存在
js
fs.existsSync(path);判断文件还是目录
js
const fullPath = path.join(dirPath, file);
const stat = fs.statSync(fullPath);
console.log(stat.isDirectory());获取文件绝对路径
js
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const filePath = path.resolve(__dirname, './file.txt');
// 或者 const filePath = path.join(__dirname, 'file.txt');获取文件内容
js
const mdData = fs.readFileSync(filePath, 'utf8');写入文件内容
js
// 写入/覆盖
fs.writeFileSync(STORE_PATH, JSON.stringify({}, null, 2));
// 追加
fs.appendFileSync(STORE_PATH, JSON.stringify(data, null, 2));