更多详细的信息可以查看http://nodejs.cn/api/fs.html#...
fs的读取文件
readFile(path,callback)
使用readFile完成一个小demo,需求:访问存在的文件把存在的文件展示出来,访问不存在的文件跳转到404页面
node代码:
http
.createServer(function (req, res) {
res.setHeader("Access-Control-Allow-Origin", "*");
let urlPath = urlLib.parse(req.url, true).path;
fs.readFile("." + urlPath, function (error, data) {
if (error) {
console.log(error);
fs.readFile("./404.html", function (error, data) {
if (error) {
console.log(error);
}
res.write(data);
res.end();
});
} else {
res.write(data);
res.end();
}
});
})
.listen(9213);
效果展示:
writeFile()写入,小demo需求:在访问8902端口的时候,将目录下的图片复制一份出来。
node代码
http
.createServer(function (req, res) {
fs.readFile("bianzu@3x.png", function (err, data) {
if (err) console.log(err);
fs.writeFile("2.png", data, (err) => {
if (err) console.log(err);
console.log("生成完毕");
res.end();
});
});
})
.listen(8902);
文件重命名 rename()
node代码
http
.createServer(function (req, res) {
fs.rename("1.png", "test.png", (err) => {
if (err) console.log(err);
console.log("修改成功");
res.end();
});
})
.listen(9092);
删除文件 unlink()
node代码
http
.createServer(function (req, res) {
fs.unlink("test.png", (err) => {
if (err) console.log(err);
console.log("删除成功");
res.end();
});
})
.listen(9093);
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。