node 常用模块及方法fs,url,http,path

http://www.cnblogs.com/mangoxin/p/5664615.html
https://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000/001434501504929883d11d84a1541c6907eefd792c0da51000

首次接触node,

赶紧把基础的又容易忘的简单的记下来

// fs 模块的常用方法,
var fs = require("fs");

fs.readFile("/home/pt/so",  "'utf-8", function (err, data) { // 异步读取文件
    // 异步读取文件 如果是文本类型,可以传一个编码类型
    // 如果不传入编码,则返回一个 Buffer对象  一个包含零个或任意个字节的数组(注意和Array不同)
    // err参数代表一个错误对象,data为undefined
    // data 的一些常用方法
    // data.toString(); // 转换成字符串   // 还可以反向转换  var buf = new Buffer(text, "utf-8")
    // data.length   // 返回字节数:单位是 bytes
    // 
    
})

var file = fs.readFileSync("/home/pt/so", "utf-8"); // 如果同步读取文件发生错误,则需要用try...catch捕获该错误
// 写入文件
fs.writeFile("output.txt", data, function (err) {
    // 第二个参数的文件内容
    // 默认按UTF-8编码写入文本文件
    // 如果传入的参数是Buffer,则写入的是二进制文件
})

如果需要获取文件的信息

var fs = require('fs');

fs.stat('sample.txt', function (err, stat) {
    if (err) {
        console.log(err);
    } else {
        // 是否是文件:
        console.log('isFile: ' + stat.isFile());
        // 是否是目录:
        console.log('isDirectory: ' + stat.isDirectory());
        if (stat.isFile()) {
            // 文件大小:
            console.log('size: ' + stat.size);
            // 创建时间, Date对象:
            console.log('birth time: ' + stat.birthtime);
            // 修改时间, Date对象:
            console.log('modified time: ' + stat.mtime);
        }
    }
});
fs.close(fd, callback) // 关闭文件
fs.ftruncate(fd, len, callback) // 截取文件
fs.unlink(path, callback) // 删除文件
fs.mkdir(path [, mode], callback) // 创建目录,mode 是目录权限 默认为0777
fs.readdir(path, callback) // 查看目录  回调函数带有两个参数err, files,err 为错误信息,files 为 目录下的文件数组列表
fs.rmdir(path, callback) // 删除目录
fs.exists(path, callback) // 判断路径是否存在 callback 参数 exists , 判断真假。
fs.appendFile(name, str, encode, callback) // name : 文件名 str : 添加的字段 encode : 设置编码 callback : 回调函数

url 模块

var url = require("url");
console.log(url.parse("http://user:pass@host.com:8080/path/to/file?query=string#hash"));
Url {
  protocol: 'http:',
  slashes: true,
  auth: 'user:pass',
  host: 'host.com:8080',
  port: '8080',
  hostname: 'host.com',
  hash: '#hash',
  search: '?query=string',  // 多个的话  "?a=2&b=3&c=4"
  query: 'query=string',      // 多个的话  "a=2&b=3&c=4"
  pathname: '/path/to/file', // 去除参数的路径
  path: '/path/to/file?query=string',  // 除域名外的路径,路由
  href: 'http://user:pass@host.com:8080/path/to/file?query=string#hash' // 完整路径
 }

path 模块

var path = require("path");
var workDir = path.resolve(".")   // 解析当前路径
var filePath = path.join(workDir, "pul", "index.html")   // 拼接路径

posted @ 2017-08-11 13:40  凉月-天  阅读(290)  评论(0编辑  收藏  举报