您的位置:首页 > Web前端 > Node.js

Node.js 学习笔记(1) 文件操作

2015-05-15 17:22 711 查看
调用nodejs中的fs模块.

读取文件

完整的读取

var fs = require('fs');
fs.readFile(filename, [options], callback)

options 默认值为'r' ,也可以设定utf8等 (以下为常见值),
'r' 读取文件,若不存在抛出异常
'r+' 读取并写入文件,若不存在抛出异常
'w'  写入文件,若不存在,创建改文件;若存在,清空原文件内容
'a'  追加写入文件,若不存在则创建改文件

<style type="text/css">p { margin-bottom: 0.25cm; line-height: 120%; }</style><p style="margin-bottom: 0cm; line-height: 100%">实例:</p><p style="margin-bottom: 0cm; line-height: 100%"><span style="font-family:Liberation Serif, serif;"><span style="font-size:14px;"><span lang="en-US">fs.readFile('./text.txt',function(err, data) {</span></span></span></p><p style="margin-bottom: 0cm; line-height: 100%"><span style="font-family:Liberation Serif, serif;"><span style="font-size:14px;"><span lang="en-US">	if(err)</span></span></span></p><p style="margin-bottom: 0cm; line-height: 100%"><span style="font-family:Liberation Serif, serif;"><span style="font-size:14px;"><span lang="en-US">		console.log('error');</span></span></span></p><p style="margin-bottom: 0cm; line-height: 100%"><span style="font-family:Liberation Serif, serif;"><span style="font-size:14px;"><span lang="en-US">	else</span></span></span></p><p style="margin-bottom: 0cm; line-height: 100%"><span style="font-family:Liberation Serif, serif;"><span style="font-size:14px;"><span lang="en-US">		console.log(data.toString());</span></span></span></p><p style="margin-bottom: 0cm; line-height: 100%"><span style="font-family:Liberation Serif, serif;"><span style="font-size:14px;"><span lang="en-US">});</span></span></span></p>


指定位置

fs.open(filename, flags, [mode], callback)
flags, mode 同readFile

实例:
var fs = require('fs');
fs.open('./message.txt','r',function (err, fd) {
	console.log(fd);
})

fs.read(fd, buffer, offset, length, position, callback)
fd :open方法所使用的回调函数中返回的文件描述符,
buffer:一个Buffer对象,指定讲文件数据读取到哪个缓冲区中
offset: 用于制定法向缓存区中写入数据时的开始写入位置(以字节为单位,整数)
length :用于指定从文件中饭读取的字节数(以字节为单位,整数)
position: 用于制定法读取文件时的开始位置(以字节为单位,整数)

callback : function (err,bytesRead,buffer){
			
			}


写文件

fs.writeFile(filename,data, [options] , callback);

data用于指定需要写入的内容,可以为一个字符串或者一个Buffer对象

fs.write同fs.read,回调函数为function(err,written, buffer)其中written同byteRead


关闭文件

fs.close(fd,[callback]) fd同上

以上都是异步的操作,若要同步的话,方法名+Sync 即可
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: