node常用模块API教程

官方文档:

一、path 模块 http://nodejs.cn/api/path.html

   path 模块提供了用于处理文件和目录的路径的实用工具。 可以使用以下方式访问它:

const path = require('path');
  • path.basename(path):返回 path 的最后一部分
    path.basename('/foo/bar/baz/asdf/quux.html');
    // 返回: 'quux.html'
  • path.dirname(path):返回 path 的目录名
    path.dirname('/foo/bar/baz/asdf/quux');
    // 返回: '/foo/bar/baz/asdf'
  • path.extname(path):返回 path 的扩展名。 如果 path 的最后一部分中没有 .,则返回空字符串。
    path.extname('index.html');
    // 返回: '.html'
    
    path.extname('index.coffee.md');
    // 返回: '.md'
    
    path.extname('index.');
    // 返回: '.'
    
    path.extname('index');
    // 返回: ''
    
    path.extname('.index');
    // 返回: ''
    
    path.extname('.index.md');
    // 返回: '.md'
  • path.join([...paths]): 使用特定于平台的分隔符作为定界符将所有给定的 path 片段连接在一起,然后规范化生成的路径。
    path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');
    // 返回: '/foo/bar/baz/asdf'
    
    path.join('foo', {}, 'bar');  // 如果任何路径片段不是字符串,则抛出 TypeError。
    // 抛出 'TypeError: Path must be a string. Received {}'
  • path.parse(path): 返回一个对象,其属性表示 path 的重要元素。
    path.parse('/home/user/dir/file.txt');
    // 返回:
    // { root: '/',
    //   dir: '/home/user/dir',
    //   base: 'file.txt',
    //   ext: '.txt',
    //   name: 'file' }
  • path.resolve([...paths]): 将路径或路径片段的序列解析为绝对路径。
    // 给定的路径序列从右到左处理,每个后续的 path 会被追加到前面,直到构建绝对路径。构建好绝对路径后,前面的片段就是废弃的。
    path.resolve('/foo/bar', './baz');
    // 返回: '/foo/bar/baz'
    
    path.resolve('/foo/bar', '/tmp/file/');
    // 返回: '/tmp/file'
    
    path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif');
    // 如果当前工作目录是 /home/myself/node,
    // 则返回 '/home/myself/node/wwwroot/static_files/gif/image.gif'

注意:有两个特殊的全局变量,__filename、__dirname。执行脚本文件时,node进程就会传入这俩变量值。

二、http 模块 http://nodejs.cn/api/http.html

三、

原文地址:https://www.cnblogs.com/wfblog/p/15813154.html