Skip to content

第1章 内置模块

fs 文件模块

导入fs模块

js
const fs = require('fs');

读取文件

js
fs.readFile(path[, options], callback);
  • 参数1:读取文件的存放路径
  • 参数2:读取文件时采用的编码格式,一般默认指定为utf8
  • 参数3:回调函数,拿到读取失败和成功的结果err dataStr
js
fs.readFile('./1.txt', 'utf8', function (err, dataStr) {
    // 打印失败的结果
    // 读取成功时,err为null
    // 读取失败时,err为错误对象,dataStr的值为undefined
    console.log(err);
    // 打印成功的结果
    console.log(dataStr);
})

写入文件

js
fs.writeFile(path, data[, option], callback);
  • 参数1:文件写入的路径
  • 参数2:写入的内容
  • 参数3:写入文件时采用的编码格式,一般默认指定为utf8
  • 参数4:回调函数,拿到写入失败的结果 err
js
fs.writeFile('./1.txt', 'Hello World!', 'utf8', function (err) {
    // 如果文件写入成功,则err为null
    // 如果文件写入失败,则err为错误信息
    console.log(err);
})

path 模块

导入模块

js
const path = require('path');

拼接路径

js
// 应使用path.join()方法拼接路径,不应使用'+'拼接
// '../'会抵消一层目录
const pathStr = path.join('/a', '/b/c', '../', './d', 'e');
console.log(pathStr);   // 输出 \a\b\d\e

// __dirname为当前文件所在目录
const pathStr2 = path.join(__dirname, './files/1.txt');
console.log(pathStr2);  // 输出 当前目录下的files文件夹下的1.txt

获取文件名

js
path.basename(path[, ext]);
  • 参数1:文件的路径
  • 参数2:文件的后缀名
js
const fpath = '/a/b/c/index.html';
const fullName = path.basename(fpath);
console.log(fullName);  // index.html

// 当有第二个参数时,获取文件名后去除后缀
const nameWithoutExt = path.basename(fpath,'.html');
console.log(nameWithoutExt);    // index

获取扩展名

js
// path.extname(path)方法可用于获取文件扩展名
const fpath = '/a/b/c/index.html';
const fext = path.extname(fpath);
console.log(fext);  // .html

url 模块

你认为这篇文章怎么样?
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0

预览:

评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v3.1.3