js实现读写
JavaScript 实现文件读写
在浏览器环境中,JavaScript 通常无法直接读写本地文件系统,但可以通过以下方法实现文件读写操作。
读取文件
使用 <input type="file"> 元素允许用户选择文件,然后通过 FileReader API 读取文件内容。
const fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.addEventListener('change', (event) => {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = (e) => {
const content = e.target.result;
console.log(content); // 文件内容
};
reader.readAsText(file); // 以文本形式读取
});
document.body.appendChild(fileInput);
写入文件
在浏览器中无法直接写入本地文件,但可以通过以下方式模拟:
- 使用
Blob和URL.createObjectURL生成下载链接。 - 使用
File System Access API(现代浏览器支持)。
// 生成并下载文件
const content = 'Hello, World!';
const blob = new Blob([content], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'example.txt'; // 下载文件名
a.click();
URL.revokeObjectURL(url); // 释放内存
Node.js 环境下的文件读写
在 Node.js 中,可以使用 fs 模块直接读写文件。
const fs = require('fs');
// 同步读取文件
const data = fs.readFileSync('file.txt', 'utf8');
console.log(data);
// 异步写入文件
fs.writeFile('output.txt', 'New content', (err) => {
if (err) throw err;
console.log('File saved');
});
使用 File System Access API(浏览器)
现代浏览器支持更高级的文件操作:

async function saveFile(content) {
const options = {
types: [{
description: 'Text Files',
accept: { 'text/plain': ['.txt'] },
}],
};
const handle = await window.showSaveFilePicker(options);
const writable = await handle.createWritable();
await writable.write(content);
await writable.close();
}
注意事项
- 浏览器环境下的文件操作需要用户交互触发(如点击事件)。
File System Access API需要 HTTPS 环境或本地开发环境。- Node.js 的
fs模块分为同步和异步方法,异步方法更适合生产环境。






