通知短信+运营短信,5秒速达,支持群发助手一键发送🚀高效触达和通知客户 广告
[TOC] ## Buffer(数据块) 可用于操作二进制 字符串 ``` var bin = new Buffer([ 0x68, 0x65, 0x6c, 0x6c, 0x6f ]); //创建二进制字符串 var str = bin.toString('utf-8'); //二进制转utf8 => "hello" var bin = new Buffer('hello', 'utf-8'); //utf转二进制 => <Buffer 68 65 6c 6c 6f> ``` ## Stream(数据流) 处理大数据 ## File System(文件系统) ``` 文件属性读写: fs.stat、fs.chmod、fs.chown 等等。 文件内容读写:fs.readFile、fs.readdir、fs.writeFile、fs.mkdir 等等。 底层文件操作:fs.open、fs.read、fs.write、fs.close 等等。 ``` nodejs 中使用异步来处理文件,通过回调函数,传递结果 1. 异步方法 ``` fs.readFile(pathname, function (err, data) { if (err) { // Deal with error. } else { // Deal with data. } }); ``` 2. 同步方法 ``` try { var data = fs.readFileSync(pathname); // Deal with data. } catch (err) { // Deal with error. } ``` ## Path(路径) 1. path.normalize 解析路径中的.与..外,还能去掉多余的斜杠 ``` var path = require("path"); console.log(path.normalize('foo/bar')); //foo\bar console.log(path.normalize('foo//baz//../bar'));; //foo\bar ``` > 在操作玩后需要用.replace(/\\/g, '/'),可是window 下的路径也是`/` 2. path.join 拼接目录 拼接目录, ``` var path = require("path"); path.join('foo/', 'baz/', '../bar'); // => "foo/bar" ``` 3. path.extname 获取文件路径的后缀 ``` path.extname('foo/bar.js'); // => ".js" ``` ## 文本编码 1. BOM的移除 ``` function readText(pathname) { var bin = fs.readFileSync(pathname); if (bin[0] === 0xEF && bin[1] === 0xBB && bin[2] === 0xBF) { bin = bin.slice(3); } return bin.toString('utf-8'); } ``` 3. GBK转UTF8 `npm install iconv-lite` ``` var iconv = require('iconv-lite'); function readGBKText(pathname) { var bin = fs.readFileSync(pathname); return iconv.decode(bin, 'gbk'); } ```