1.File System模块介绍
重命名文件
fs.rename(path1, path2, [callback])
var BASE_DIR = __dirname; var fs = require("fs"); fs.rename(BASE_DIR + '/test.txt', BASE_DIR + 'zula.txt', function(err) { if (err) throw err; console.log('rename complete'); }) //path1 源文件path //path2 重命名后的文件名 //同步调用方法fs.renameSync(path1, path2)
修改文件权限和文件权限属组
fs.chmod(path, mode, [callback])
var BASE_DIR = __dirname; var fs = require("fs"); fs.chmod(BASE_DIR + 'test.txt', '777', function(err) { if (err) throw err; console.log('rename complete'); }) //将文件test.txt的权限改为777
fs.chown(path, uid, gid, [callback]) (uid=>user git=>group) 修改文件的用户名和属组
获取文件元信息
fs.stat(path, [callback])
var BASE_DIR = __dirname; var fs = require("fs"); fs.stat(BASE_DIR + '/test.txt', function(err, stats){ if(err) throw err; console.log(stats); })
Stats { dev: 3737947054, //设备编号 mode: 33206, //文件类型和存储权限 nlink: 1, //连到该文件的硬连接数目 uid: 0, //用户id gid: 0, //组id rdev: 0, //若该文件为设备文件,则为其设备编号,否则为0 blksize: undefined, //文件系统I/O缓冲区大小 ino: 844424930933926, //节点 size: 32270, //文件节数大小 blocks: undefined, //块数 atimeMs: 1505465717925.0657, mtimeMs: 1502075853051.4958, ctimeMs: 1505465717928.066, birthtimeMs: 1505465717925.0657, atime: 2017-09-15T08:55:17.925Z, //最后一次访问时间 mtime: 2017-08-07T03:17:33.051Z, //最后一次更改时间 ctime: 2017-09-15T08:55:17.928Z, //最后一次改变时间(文件的属性) birthtime: 2017-09-15T08:55:17.925Z }
读取文件数据
fs.readFile(path,[callback])
验证文件存在
fs.exists(path,[callback]
fs.exists(BASE_DIR + '/test.txt', function(existBool) { if(existBool) { console.log('test.txt exist'); } else { console.log('test.txt not exist'); } })
删除文件
fs.unlink(path,[callback])
文件读写
fs.write(fd, buffer, offset, length, position, [callback])
将buffer缓冲器内容写入fs文件,postion指明将数据写入文件从头部算起的偏移位置, 若postion为null, 数据将从当前位置开始写入。回调函数接收两个参数(err, written),其中written标识有多少字节的数据已经写入。fs.read(fd, buffer, offset, length, position, [callback])
回调函数(err, bytesRead)
2.图片和文件上传
实例详解图片和文件的上传功能
- 创建index.html 上传图片,提交到’/upload’
<div id="main_content">
<form enctype="multipart/form-data" action="/upload">
<input type="file" name="image">
<input type="submit" id="upload" value="上传图片">
</form>
</div>
- 创建show_image.html,显示上传后的图片
<div id="main_content">
<div id="show_image">
<img src="./uploadFile/logo.jpg" alt="upload image">
</div>
</div>
- 路由处理upload方法
function upload(req, res) {
var timestamp = Date.parse(new Date());
var form = new formidable.IncomingForm();
form.uploadDir = BASE_DIR + '/uploadFile/';
form.parse(req, function(error, fields, files) {
var fileName = timestamp + '_' + files.image.name;
try{
fs.renameSync(files.image.path, form.uploadDir + fileName);
}catch(e){
console.log(e);
}
res.render('show_image.jade',{'imgUrl':'/uploadFile/' + fileName});
});
}
注意: 文件处理一定要使用try catch
3.jade模板
- index.jade
html
head
meta(charset="utf-8")
title Node.js Upload
link(rel="stylesheet", href="/static/style.css")
body
div#main_content
div
form(enctype="multipart/form-data", action="/upload", method="post")
input(type="file", name="image")
图片名称
input(type="text", name="name")
input(type="submit", id="upload", value="上传图片")
- show_image.jade
html
head
meta(charset="utf-8")
title Node.js Show Image
link(rel="stylesheet",href="static/style.css")
script(src="static/jquery-1.8.3.min.js")
body
div#main_content
h2 图片展示
div
img(src='#{imgUrl}',alt='upload file')
- index.js处理jade
res.render = function(template, options) {
//同步获取jade模板文件数据
var str = fs.readFileSync(template, 'utf8');
//获取jade模板编译处理函数
var fn = jade.compile(str, { filename: template, pretty: true });
//调用fn函数,将jade模板转化为html文件数据字符
var page = fn(options);
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(page);
}
---
//调用
res.render('index.jade',{'user':'zula'});
4. 上传图片存在的问题
路径存在中午或者上传图片的名称含中文时,可以正常上传,但无法展示图片信息。
获取url时转码
var pathname = decodeURI(url.parse(req.url).pathname);
修改static_moudle.js
exports.getStaticFile = function(pathname, req, res){ pathname = decodeURI(pathname) --- }
在windows运行时会出现异常
fs.js:330
return binding.rename(pathModule._makeLong(oldPath),
^
Error: ENOENT, no such file or directory 'C:\Users\dd\AppData\Local\Temp\68ef9
377b965f242cf7ae5b4595f31’
- 将代码放在c盘,确保在一个磁盘
5.文件读写
通过web客户端可以在线进行对文件编辑操作,实时地对服务器文件进行更新,实现类似本地文件编辑功能,同时可以保存文件,下次进入可以同样进行更改。
//核心代码
io = socket.listen(app);
io.sockets.on('connection', function (socket) {
var message = fs.readFileSync(filePath, 'utf8');
socket.emit('change_from_server', { msg: message});
socket.on('success', function (data) {
console.log(data.msg);
});
socket.on('data', function (data) {
writeFile(data.msg, function(){
socket.emit('change_from_server', { msg: data.msg});
});
});
});