fs(文件系统)

通过 require(‘fs’) 使用该模块。 所有的方法都有异步和同步的形式。

异步版本:

1
2
3
4
5
6
const fs = require('fs');

fs.unlink('/tmp/hello', (err) => {
if (err) throw err;
console.log('successfully deleted /tmp/hello');
});

同步版本:

1
2
3
4
const fs = require('fs');

fs.unlinkSync('/tmp/hello');
console.log('successfully deleted /tmp/hello');

基本方法

readFile

1
2
3
4
5
6
7
fs.readFile(file[, options], callback)

file <String> | <Buffer> | <Integer> 文件名或文件描述符
options <Object> | <String>
encoding <String> | <Null> 默认 = null
flag <String> 默认 = 'r'
callback <Function>

1
2
3
4
fs.readFile('/etc/passwd', (err, data) => {
if (err) throw err;
console.log(data);
});

writeFile

1
2
3
4
5
6
7
8
fs.writeFile(file, data\[, options], callback)
file <String> | <Buffer> | <Integer> 文件名或文件描述符
data <String> | <Buffer>
options <Object> | <String>
encoding <String> | <Null> 默认 = 'utf8'
mode <Integer> 默认 = 0o666
flag <String> 默认 = 'w'
callback <Function>

1
2
3
4
fs.writeFile('message.txt', 'Hello Node.js', (err) => {
if (err) throw err;
console.log('It\'s saved!');
});

注意点

不建议在调用 fs.open() 、 fs.readFile() 或 fs.writeFile()
之前使用 fs.access() 检查一个文件的可访问性。 如此处理会造成紊乱情况,
因为其他进程可能在两个调用之间改变该文件的状态。 作为替代,
用户代码应该直接打开/读取/写入文件,当文件无法访问时再处理错误。

评论和共享

终极异步方案

JavaScript异步编程一直是一件很麻烦的事,从最早的回调函数,到 Promise 对象,
再到 Generator 函数,每次都有所改进。但总感觉缺点什么。

直到 async/await 出现,很多人认为它是异步操作的终极解决方案。

async 应该会在 ECMAScript 7 引入。在 NodeJs v7.4.0 正式加入 NodeJs 大家庭。

async 是 Generator 函数的语法糖

1
2
3
4
5
6
7
8
9
10
var fs = require('fs');

var readFile = function (fileName){
return new Promise(function (resolve, reject){
fs.readFile(fileName, function(error, data){
if (error) reject(error);
resolve(data);
});
});
};

Generator 写法:

1
2
3
4
5
6
7
8
var co = require('co');
var gen = function* (){
var f1 = yield readFile('/etc/fstab');
var f2 = yield readFile('/etc/shells');
console.log(f1.toString());
console.log(f2.toString());
};
co(gen);

写成 async 函数,就像下面这样:

1
2
3
4
5
6
var asyncReadFile = async function (){
var f1 = await readFile('/etc/fstab');
var f2 = await readFile('/etc/shells');
console.log(f1.toString());
console.log(f2.toString());
};

其实就是把 * 替换成 async ,把 yield 换成 await。而且自带执行器
(Generator 函数的执行必须依靠执行器,所以才有了 co 函数库)。

async 函数用法

  • 同 Generator 函数一样,async 函数返回一个 Promise 对象。
    所以调用 async 函数的函数也要处理 Promise 对象。

  • 用 try…catch 来处理 Promise 对象 rejected

  • await 命令只能用在 async 函数之中,如果用在普通函数,就会报错。

  • 将 forEach 方法的参数改成 async 函数不能够实现继发执行。应该采用 for 循环。

  • 希望多个请求并发执行,可以使用 Promise.all 方法。

评论和共享

首先搭建一个express的项目

添加一个index.html


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</body>
</html>

安装socket.io插件


1
npm install --save socket.io

在index.js 中添加代码


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
res.sendfile('index.html');
});

io.on('connection', function(socket){
console.log('a user connected');
});

http.listen(3000, function(){
console.log('listening on *:3000');
});

在index.html中添加代码


1
2
3
4
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>

这样就能看到用户链接信息了

将index.js改成


1
2
3
4
5
6
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
});

这样就能看到用户退出信息了

在index.html中添加代码


1
2
3
4
5
6
7
8
9
10
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
</script>

1
2
3
4
5
6
io.on('connection', function(socket){
socket.on('chat message', function(msg){
console.log('message: ' + msg);
});
//服务器打印消息
});

完成发送给服务器数据

在index.html中添加代码


1
2
3
4
5
6
7
8
9
10
11
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>

1
2
3
4
5
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});

完成服务器给前端返回数据

评论和共享

  • 第 1 页 共 1 页
作者的图片

Archie Shi

Nothing to say


Front-End Development Engineer