node中的内置模块path和fs

一、path模块

1. 常用方法介绍

Node中的path模块是用来操作文件路径的内置模块,主要用于字符串路径操作,其有多种用法用来返回不同的路径信息。

  1. path.join

path.join()方法主要用于连接路径。该方法的主要作用就是将所有传入的路径片段连接在一起,然后规范化生成的路径。需要注意的是,在Join操作中’/'会被当做根路径。

例如:

var path = require('path');
var p = path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');
console.log(p);  // 输出: '/foo/bar/baz/asdf'
  1. path.basename

path.basename()方法主要用于获取路径中的文件名。在提取文件名的同时,也可以使用选项参数来去除文件的扩展名。

例如:

var path = require('path');
console.log(path.basename('/foo/bar/baz/asdf/quux.html')); // 输出: 'quux.html'
console.log(path.basename('/foo/bar/baz/asdf/quux.html', '.html')); // 输出: 'quux'
  1. path.extname

path.extname()方法主要用于获取路径中文件的扩展名。

例如:

var path = require('path');
console.log(path.extname('index.html')); // 输出: '.html'
console.log(path.extname('index.coffee.md')); // 输出: '.md'
console.log(path.extname('index.')); // 输出: '.'
console.log(path.extname('index')); // 输出: ''
console.log(path.extname('.index')); // 输出: ''

有了path模块,我们就可以方便地进行文件路径的操作,对于文件系统的操作无疑提供了很大的便利。只要掌握了各个方法的特点和使用方式,就可以灵活应用于实际情况中。

2.__dirname

在Node.js中,__dirname是一个全局变量,它提供了当前执行脚本所在的目录的绝对路径。这个全局变量的值和你在命令行中所在的位置没有任何关系,它只和执行的node脚本有关。

__dirname的主要用处是用来构建文件或者目录的路径。因为无论你的进程在哪里运行,__dirname始终被设置为被执行的.js文件所在的文件夹的绝对路径,这使得它比较可靠和方便。

例如:

假设你有以下文件结构:


- /home/user/project
  - server.js
  - /assets
    - style.css

而你在/home/user/project下运行了一段如下的node.js代码:

console.log(__dirname);

无论你在哪里执行上述命令(例如在项目的父目录或者系统的根目录),它都将输出:“/home/user/project”,因为这就是server.js文件所在的目录。

同样,__dirname适合用来动态地构建文件路径,例如,如果你想在server.js中读取style.css文件,

var fs = require('fs');
var path = require('path');

fs.readFile(path.join(__dirname, 'assets/style.css'), function(err, data) {
    
    
  if (err) {
    
    
    throw err;
  }
  console.log(data);
});

上述代码中,我们使用了path.join()方法,这是因为不同的操作系统文件路径的分隔符不同,path.join()方法能确保我们总是得到正确的文件路径。

二、fs模块

Node.js fs(文件系统)模块可以对系统文件进行I/O操作。所有的文件系统操作都提供了异步(非阻塞)和同步(阻塞)两种形式。

fs模块提供的API基本上可以分为以下三类:

  • 文件属性读写 API
  • 文件内容读写 API
  • 目录操作 API

下面详细介绍一下fs.readFile和fs.writeFile的用法:

  1. fs.readFile:这个方法主要是用来读取文件内容的。语法如下:
fs.readFile(path[, options], callback)
  • path - 文件的地址
  • options - 选项,包括 encoding(文件编码)、flag(文件操作符,默认 ‘r’)
  • callback - 数据回调函数,参数为(err, data),err 为错误信息,data为读取到的数据

读取一个文本文件的例子:

const fs = require('fs');
fs.readFile('/path/to/file.txt', 'utf8', function(err, data){
    
    
    if (err) throw err;
    console.log(data);
});
  1. fs.writeFile:这个方法主要是用来写入文件内容的。语法如下:
fs.writeFile(file, data[, options], callback)
  • file - 文件路径
  • data - 要写入的内容,可以是字符串或 Buffer 对象
  • options - 选项,包括 encoding(编码)、mode(权限)、flag(操作符)等
  • callback - 回调函数

写入一个文本文件的例子:

const fs = require('fs');
fs.writeFile('/path/to/file.txt', 'Hello World', function(err){
    
    
    if (err) throw err;
    console.log('The file has been saved!');
});

在实际开发场景,假设我们想输入特定数据到一个log文件,同时也要读取其内容展示到客户端,这时候我们就可以使用fs模块。示例代码如下:

const fs = require('fs');
let contentToWrite = 'Hello, this is a log message!';
let logFilePath = '/path/to/log.txt';

// 写入 log
fs.writeFile(logFilePath, contentToWrite, function(err){
    
    
    if (err) throw err;
    console.log('Log has been written to the file!');
});

// 读取 log
fs.readFile(logFilePath, 'utf8', function(err, data){
    
    
    if (err) throw err;
    console.log('Log Content:', data);
});

三、node中的模块介绍

可能看到这里,0基础的小伙伴会有些疑惑,这些path,fs哪来的,怎么引入了就可以直接使用呢?那么接下来就简单介绍一下node中的模块

在 Node.js 中,存在三种主要类型的模块,它们是:

  1. 内置核心模块:这些模块是与 Node.js 自身一起提供的,不需要额外安装就可以使用。如 HTTP、path、fs、stream 等。

例如,使用 http 模块创建 HTTP 服务器:

const http = require('http');

http.createServer((req, res) => {
    
    
  res.writeHead(200, {
    
    'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(8080);
  1. 本地模块:这些模块是由开发人员自己编写的,用于组织自身应用程序的代码。它们可以是一组经常使用的函数,或者是提供特定功能的对象。

例如,创建一个名为 greeting 的本地模块,它包含一个函数,用来返回问候语:

// greeting.js
module.exports.sayHello = function(name){
    
    
    return "Hello, " + name;
}

在另一个文件中引用和使用它:

// app.js
const greeting = require('./greeting');

console.log(greeting.sayHello("John"));
  1. 第三方模块:这些模块是从 npm (Node Package Manager) 仓库安装并使用的模块。这些模块由社区开发人员创建并维护,用于提供在许多应用中都会使用到的功能。

例如,安装并使用 express 模块来创建一个简单的 web 服务器:

// 使用 npm 安装 express
// npm install express

const express = require('express');
const app = express();

app.get('/', (req, res) => {
    
    
  res.send('Hello World!');
});

app.listen(3000, () => {
    
    
  console.log('Server is running on port 3000');
});

猜你喜欢

转载自blog.csdn.net/jieyucx/article/details/131608848