fs读取文件
process.cwd() 是 Node.js 中的一个方法,它返回 Node.js 进程的当前工作目录。这个工作目录通常是启动 Node.js 进程时所在的目录。
const fs = require('fs');
const path = require('path');// 读取指定目录
const configPath = path.join(process.cwd(), 'config.json');
// const configPath = path.join(process.cwd(), 'src/config.json');
// 读取文件
const config = fs.readFileSync(configPath, 'utf-8');
console.log(config);
fs 读取目录
const fs = require('fs');
const path = require('path');// 指定要读取的目录路径
const directoryPath = './exampleDirectory';// 使用 fs.readdir() 读取目录
fs.readdir(directoryPath, (err, files) => {if (err) {console.error(`读取目录时发生错误: ${err}`);return;}// 文件数组包含了目录中的所有文件和子目录files.forEach(file => {console.log(file);});
});// 异步/等待版本的读取目录
// (注意:此示例使用了 async/await,因此需要在异步函数中使用)
async function readDirectoryAsync() {try {const files = await fs.promises.readdir(directoryPath);files.forEach(file => {console.log(file);});} catch (err) {console.error(`异步读取目录时发生错误: ${err}`);}
}// 调用异步函数
readDirectoryAsync();
fs判断是否为文件夹
const fs = require('fs');const path = './example/folder'; // 要检查的路径fs.stat(path, (err, stats) => {if (err) {console.error('发生错误:', err);return;}if (stats.isDirectory()) {console.log('这是一个文件夹');} else {console.log('这不是一个文件夹');}
});
fs 获取文件名
const fs = require('fs');
const path = require('path');// 假设你有一个包含路径的文件名字符串
const filePath = '/example/directory/test.txt';// 使用 path.basename 获取文件名
const fileName = path.basename(filePath);console.log(fileName); // 输出: test.txt
获取文件扩展名
const path = require('path');// 假设你有一个包含路径的文件名字符串
const filePath = '/example/directory/牡蛎.txt';// 使用 path.extname 获取文件扩展名
const fileExtension = path.extname(filePath);console.log(fileExtension); // 输出: .txt
实践:
const fs = require('fs');
const path = require('path');// 使用 fs.readdir() 读取目录
const readdir = (directoryPath, isRoot) => fs.readdir(directoryPath, (err, files) => {if (err) {console.error(`读取目录时发生错误: ${err}`);return;}// 文件数组包含了目录中的所有文件和子目录files.forEach(file => {const pPath = isRoot ? path.join(process.cwd(), `${directoryPath}/${file}`) : `${directoryPath}/${file}`;fs.stat(pPath, (err, stats) => {if (err) {console.error('发生错误:', err);return;}if (stats.isDirectory()) {console.log('文件夹:', pPath);readdir(pPath);} else {const readFile = fs.readFileSync(pPath, 'utf-8');console.log(`------>READ FILE ${pPath} START:<------\n`, readFile, `\n------>READ FILE ${pPath} END<------\n`);}})});
});readdir('./src', true);
运行脚本即可