文件读写

Node.js 文件读写

推荐使用 node-fs-extra 来扩展原生的 fs 模块尚未提供的功能,

读取文件

const { promisify } = require('util');
const fs = require('fs');
const readFileAsync = promisify(fs.readFile); // (A)
const filePath = process.argv[2];
readFileAsync(filePath, { encoding: 'utf8' })
.then(text => {
console.log('CONTENT:', text);
})
.catch(err => {
console.log('ERROR:', err);
});

如果文件不存在的话则会报错,有时候我们需要首先判断文件是否存在:

fs.exists(path, callback);
fs.existsSync(path);

JSON

const fs = require('fs-extra');
const file = '/tmp/this/path/does/not/exist/file.json';
fs.outputJson(file, { name: 'JP' }, err => {
console.log(err); // => null
fs.readJson(file, (err, data) => {
if (err) return console.error(err);
console.log(data.name); // => JP
});
});
// With Promises:
fs.outputJson(file, { name: 'JP' })
.then(() => fs.readJson(file))
.then(data => {
console.log(data.name); // => JP
})
.catch(err => {
console.error(err);
});
function processFile(inputFile) {
var fs = require('fs'),
readline = require('readline'),
instream = fs.createReadStream(inputFile),
outstream = new (require('stream'))(),
rl = readline.createInterface(instream, outstream);
rl.on('line', function(line) {
console.log(line);
});
rl.on('close', function(line) {
console.log(line);
console.log('done reading file.');
});
}
processFile('/path/to/a/input/file.txt');
fs.readFile('input.txt', 'utf8', function(err, data) {
if (err) throw err;
console.log(data);
});

写入文件

const fs = require('fs');
fs.writeFile('/tmp/test', 'Hey there!', function(err) {
if (err) {
return console.log(err);
}
console.log('The file was saved!');
});

我们也可以直接使用 fs-extra 提供的 outputFile 函数来自动创建不存在的文件:

const fs = require('fs-extra');
const file = '/tmp/this/path/does/not/exist/file.txt';
fs.outputFile(file, 'hello!', err => {
console.log(err); // => null
fs.readFile(file, 'utf8', (err, data) => {
if (err) return console.error(err);
console.log(data); // => hello!
});
});
// With Promises:
fs.outputFile(file, 'hello!')
.then(() => fs.readFile(file, 'utf8'))
.then(data => {
console.log(data); // => hello!
})
.catch(err => {
console.error(err);
});