1 添加一个文件内容 var fs = require('fs'); fs.open(Date.now() + '.txt', 'a+', function (err, fd) { //创建一个文件件 名称以时间戳的形式存在 if (err) throw err; console.log(fd); })
2 读取文件 读取文本文件时, 如.txt, .js, .json等文件, 直接使用readFile就可以获取文件的内容。
var fs = require('fs');
fs.readFile('./data.txt', 'utf-8', function (err, fd) {
if (err) throw err;
console.log(data);
})
3 获取文件夹信息 前提是创建好的文件夹信息
fs.stat('./index.js', function (err, stats) {
if (err) {
console.log('路径结果');
throw err;
}
console.log(stats);
console.log('isfile:' + stats.isFile());
console.log('isdir:' + stats.isDirectory()); // 是否为文件夹
console.log('size',
stats.isFile(),
stats.isDirectory(),
stats.isBlockDevice(),
stats.isCharacterDevice(),
stats.isSymbolicLink(),
stats.isFIFO(),
stats.isSocket())
});
4 显示所有文件夹信息
fs.rmdir('./', function (err, files) {
if (err) throw err;
console.log(files)
})
5 读取文件到缓冲区中
var buf = new Buffer(225);
fs.read(fd, buf, 0, 9, 3, function (err, bytesRead, buffer) {
console.log(buf.slice(0, bytesRead).toString());
});
var buff = new Buffer(225);
//位置设置为null会默认从文件当前位置读取
fs.read(fd, buff, 0, 3, null, function (err, bytesRead, buffer) {
console.log(buff.slice(0, bytesRead).toString());
});
fs.writeFileSync('./index.json',
JSON.stringify({
"perception": {
"inputText": {
"text": "附近的酒店"
},
"inputImage": {
"url": "imageUrl"
},
"selfInfo": {
"location": {
"city": "北京",
"province": "北京",
"street": "信息路"
}
}
}
}, null, 4))
var JsonObj = JSON.parse(fs.readFileSync('./index.json'));
console.log(JSON.stringify(JsonObj, null, 4));
});