Node.js 的 fs
模块提供了与文件系统进行交互的功能。以下是一些常见的操作示例代码:
1. 读取文件内容
异步读取文件
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
同步读取文件
const fs = require('fs');
try {
const data = fs.readFileSync('example.txt', 'utf8');
console.log(data);
} catch (err) {
console.error(err);
}
2. 写入文件内容
异步写入文件
const fs = require('fs');
const content = 'Some content to write into the file';
fs.writeFile('example.txt', content, 'utf8', (err) => {
if (err) {
console.error(err);
return;
}
console.log('File has been written');
});
同步写入文件
const fs = require('fs');
const content = 'Some content to write into the file';
try {
fs.writeFileSync('example.txt', content, 'utf8');
console.log('File has been written');
} catch (err) {
console.error(err);
}
3. 追加内容到文件
异步追加内容
const fs = require('fs');
const content = '\nAdditional content to append';
fs.appendFile('example.txt', content, 'utf8', (err) => {
if (err) {
console.error(err);
return;
}
console.log('Content has been appended');
});
同步追加内容
const fs = require('fs');
const content = '\nAdditional content to append';
try {
fs.appendFileSync('example.txt', content, 'utf8');
console.log('Content has been appended');
} catch (err) {
console.error(err);
}
4. 删除文件
异步删除文件
const fs = require('fs');
fs.unlink('example.txt', (err) => {
if (err) {
console.error(err);
return;
}
console.log('File has been deleted');
});
同步删除文件
const fs = require('fs');
try {
fs.unlinkSync('example.txt');
console.log('File has been deleted');
} catch (err) {
console.error(err);
}
5. 创建目录
异步创建目录
const fs = require('fs');
fs.mkdir('exampleDir', {
recursive: true }, (err) => {
if (err) {
console.error(err);
return;
}
console.log('Directory has been created');
});
同步创建目录
const fs = require('fs');
try {
fs.mkdirSync('exampleDir', {
recursive: true });
console.log('Directory has been created');
} catch (err) {
console.error(err);
}
6. 读取目录内容
异步读取目录
const fs = require('fs');
fs.readdir('exampleDir', (err, files) => {
if (err) {
console.error(err);
return;
}
console.log(files);
});
同步读取目录
const fs = require('fs');
try {
const files = fs.readdirSync('exampleDir');
console.log(files);
} catch (err) {
console.error(err);
}
7. 设置文件权限
异步设置文件权限
const fs = require('fs');
fs.chmod('example.txt', 0o755, (err) => {
if (err) {
console.error(err);
return;
}
console.log('File permissions have been changed');
});
同步设置文件权限
const fs = require('fs');
try {
fs.chmodSync('example.txt', 0o755);
console.log('File permissions have been changed');
} catch (err) {
console.error(err);
}
8. 文件流操作
读取文件流
const fs = require('fs');
const readStream = fs.createReadStream('example.txt', 'utf8');
readStream.on('data', (chunk) => {
console.log(chunk);
});
readStream.on('end', () => {
console.log('No more data to read');
});
readStream.on('error', (err) => {
console.error(err);
});
写入文件流
const fs = require('fs');
const writeStream = fs.createWriteStream('example.txt');
writeStream.write('This is the first line\n');
writeStream.write('This is the second line\n');
writeStream.end('This is the last line\n');
writeStream.on('finish', () => {
console.log('All writes are now complete.');
});
writeStream.on('error', (err) => {
console.error(err);
});
9. 监视文件变化
监视文件
const fs = require('fs');
fs.watch('example.txt', (eventType, filename) => {
if (filename) {
console.log(`${
filename} file Changed: ${
eventType}`);
}
});
监视目录
const fs = require('fs');
fs.watch('exampleDir', (eventType, filename) => {
if (filename) {
console.log(`${
filename} file Changed: ${
eventType}`);
}
});
10. 读取文件状态(获取文件信息)
异步读取文件状态
const fs = require('fs');
fs.stat('example.txt', (err, stats) => {
if (err) {
console.error(err);
return;
}
console.log(`File Size: ${
stats.size}`);
console.log(`File Permissions: ${
stats.mode}`);
console.log(`Is File: ${
stats.isFile()}`);
console.log(`Is Directory: ${
stats.isDirectory()}`);
});
同步读取文件状态
const fs = require('fs');
try {
const stats = fs.statSync('example.txt');
console.log(`File Size: ${
stats.size}`);
console.log(`File Permissions: ${
stats.mode}`);
console.log(`Is File: ${
stats.isFile()}`);
console.log(`Is Directory: ${
stats.isDirectory()}`);
} catch (err) {
console.error(err);
}
11. 重命名文件或目录
异步重命名
const fs = require('fs');
fs.rename('oldName.txt', 'newName.txt', (err) => {
if (err) {
console.error(err);
return;
}
console.log('File has been renamed');
});
同步重命名
const fs = require('fs');
try {
fs.renameSync('oldName.txt', 'newName.txt');
console.log('File has been renamed');
} catch (err) {
console.error(err);
}
12. 删除目录
异步删除目录
const fs = require('fs');
fs.rmdir('exampleDir', {
recursive: true }, (err) => {
if (err) {
console.error(err);
return;
}
console.log('Directory has been deleted');
});
同步删除目录
const fs = require('fs');
try {
fs.rmdirSync('exampleDir', {
recursive: true });
console.log('Directory has been deleted');
} catch (err) {
console.error(err);
}
13. 复制文件
异步复制文件
const fs = require('fs');
fs.copyFile('source.txt', 'destination.txt', (err) => {
if (err) {
console.error(err);
return;
}
console.log('File has been copied');
});
同步复制文件
const fs = require('fs');
try {
fs.copyFileSync('source.txt', 'destination.txt');
console.log('File has been copied');
} catch (err) {
console.error(err);
}
14. 移动文件(通过重命名实现)
异步移动文件
const fs = require('fs');
fs.rename('source.txt', 'destination.txt', (err) => {
if (err) {
console.error(err);
return;
}
console.log('File has been moved');
});
同步移动文件
const fs = require('fs');
try {
fs.renameSync('source.txt', 'destination.txt');
console.log('File has been moved');
} catch (err) {
console.error(err);
}
15. 使用 fs.promises
处理异步操作
Node.js 提供了 fs.promises
API,使得文件系统操作可以使用 async/await
语法。
读取文件内容
const fs = require('fs').promises;
async function readFile() {
try {
const data = await fs.readFile('example.txt', 'utf8');
console.log(data);
} catch (err) {
console.error(err);
}
}
readFile();
写入文件内容
const fs = require('fs').promises;
async function writeFile() {
try {
await fs.writeFile('example.txt', 'Some content to write into the file', 'utf8');
console.log('File has been written');
} catch (err) {
console.error(err);
}
}
writeFile();
追加内容到文件
const fs = require('fs').promises;
async function appendFile() {
try {
await fs.appendFile('example.txt', '\nAdditional content to append', 'utf8');
console.log('Content has been appended');
} catch (err) {
console.error(err);
}
}
appendFile();
删除文件
const fs = require('fs').promises;
async function deleteFile() {
try {
await fs.unlink('example.txt');
console.log('File has been deleted');
} catch (err) {
console.error(err);
}
}
deleteFile();
创建目录
const fs = require('fs').promises;
async function createDirectory() {
try {
await fs.mkdir('exampleDir', {
recursive: true });
console.log('Directory has been created');
} catch (err) {
console.error(err);
}
}
createDirectory();
读取目录内容
const fs = require('fs').promises;
async function readDirectory() {
try {
const files = await fs.readdir('exampleDir');
console.log(files);
} catch (err) {
console.error(err);
}
}
readDirectory();
16. 处理文件系统的错误
在处理文件系统操作时,处理错误是非常重要的。以下是一些常见的错误处理示例:
异步操作中的错误处理
const fs = require('fs');
fs.readFile('nonexistent.txt', 'utf8', (err, data) => {
if (err) {
if (err.code === 'ENOENT') {
console.error('File not found');
} else {
console.error(err);
}
return;
}
console.log(data);
});
同步操作中的错误处理
const fs = require('fs');
try {
const data = fs.readFileSync('nonexistent.txt', 'utf8');
console.log(data);
} catch (err) {
if (err.code === 'ENOENT') {
console.error('File not found');
} else {
console.error(err);
}
}
使用 fs.promises
的错误处理
const fs = require('fs').promises;
async function readFile() {
try {
const data = await fs.readFile('nonexistent.txt', 'utf8');
console.log(data);
} catch (err) {
if (err.code === 'ENOENT') {
console.error('File not found');
} else {
console.error(err);
}
}
}
readFile();