Home  >  Article  >  Web Front-end  >  Detailed explanation of commonly used APIs of Process, Path and File System modules in Node.js

Detailed explanation of commonly used APIs of Process, Path and File System modules in Node.js

青灯夜游
青灯夜游forward
2021-04-12 10:10:191688browse

This article will introduce to you the commonly used APIs of Process, Path and File System modules in Nodejs. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Detailed explanation of commonly used APIs of Process, Path and File System modules in Node.js

Related recommendations: "nodejs Tutorial"

When you use Node for daily development, you will use some file systems, Basic APIs such as path operations are summarized here to facilitate everyone's understanding and direct use.

Here we only introduce the most commonly used ones, not all of them. If you want to see more comprehensive information, just look at the official documentation.

Try not to talk nonsense and write more code.

Process module


First introduce the process module, which provides global environment information related to the current Node process. Used in later APIs.

// 内置模块,直接使用
const process = require('process');

process.cwd()

This is a function that returns the directory where the current Node process is executed. Here is an example of a common scenario:

A Node module A is published through NPM, and the module A is used in project B. When you need to operate files under the B project in A, you can use process.cwd() to obtain the path of the B project.

const cwd = process.cwd(); // 输出:/Users/xiaolian/Code/node-api-test

process.argv

When the terminal executes the command through Node, the incoming command line parameters can be obtained through process.argv. The return value is an array:

  • 0: Node path (generally not used, just ignore it)
  • 1: The executed JS file path (generally not used, just ignore it) )
  • 2~n: The parameters of the actual incoming command**

So, we only need to get them from process.argv[2] . This is generally used :

const args = process.argv.slice(2);

Get the parameters we want directly.

process.env

Returns an object that stores all information related to the current environment and is rarely used directly.

Generally we will mount some variables on process.env to identify the current environment. For example, the most common use is process.env.NODE_ENV to distinguish development and production. In the source code of vue-cli, we often see process.env.VUE_CLI_DEBUG indicating whether the current mode is DEBUG.

Here is a webpack plug-in DefinePlugin. In the daily build process, we often use this plug-in to inject different global variables to execute different build processes, and in the code The process.env.xxx will be replaced with a specific value, and the deadCode will be removed during the Terser compression stage to optimize the code size.

process.platform

This is not used much. It returns the current system information. The enumeration value is as follows:

console.log(process.platform);

// 'aix'
// 'darwin'  - macOS
// 'freebsd'
// 'linux' - linux
// 'openbsd'
// 'sunos'
// 'win32' - windows

Path module


// 内置模块,直接使用
const path = require('path');

Almost path-related operations in Node will use this module.

Here are the 5 most commonly used ones:

path.join(...paths)

path.joinThe function is to combine multiple incoming paths into a complete path.

const dPath = path.join('template', 'aaa', 'bbb', 'ccc', 'd.js');
// 输出: template/aaa/bbb/ccc/d.js

Let’s look at a very common scenario. We need to get the package.json file of the current project, and we can get its path like this:

const pkgPath = path.join(process.cwd(), './package.json');
// 输出: /Users/xiaolian/Code/node-api-test/package.json

path.join You can pass in any number of paths, such as:

['package.json', 'README.md'].forEach(fileName => {
  const templateFilePath = path.join(process.cwd(), 'template', fileName);
  console.log(templateFilePath);
});
// 输出: /Users/xiaolian/Code/node-api-test/template/package.json
// 输出: /Users/xiaolian/Code/node-api-test/template/README.md

path.resolve(...paths)

path.resovle and The difference between path.join is that its function is to splice multiple incoming paths and the current execution path into a complete absolute path.

Suppose I now index.js is in the scripts directory, and then I execute node scripts/index.js in the root directory, it The code is as follows:

const dPath = path.resolve('aaa', 'bbb', 'ccc', 'd.js');
// 输出:  /Users/xiaolian/Code/node-api-test/aaa/bbb/ccc/d.js

Generally, when the first parameter of path.resolve is ./, you can directly understand and path. join(processs.cwd(), '') behaves consistently.

path.basename(path[, ext])

path.basename Returns the last path name of the specified path , where the second parameter ext is optional and represents the file extension. For example:

console.log(path.basename('scripts/index.js'));  // index.js
console.log(path.basename('scripts/index.js', '.js'));  // 匹配到 .js,返回 index
console.log(path.basename('scripts/index.js', '.json'));  // 没匹配到,返回 index.js

path.dirname(path)

corresponds to path.basename, and returns the last one of the specified path The path before the pathname. for example:

console.log(path.basename('scripts/index.js'));  // scripts
console.log(path.basename('scripts/hook/index.js'));  // scripts/hook

path.extname(path)

path.basename 对应,返回指定 path 最后一个路径名的文件扩展名(含小数点 .)。比如:

console.log(path.basename('scripts/index.js'));  // .js
console.log(path.basename('README.md'));  // .md

对比

最后再来对比一下各个路径相关的 API 的区别。

项目 A 的目录结构如下:

├── scripts
│   └── index.js
├── src
│   └── index.js
├── package.json
├── README.md

scripts/index.js 的代码如下:

const path = require('path');

console.log(path.join('package.json'));
console.log(path.resolve('package.json'));
console.log(path.join('src', 'index.js'));
console.log(path.resolve('src', 'index.js'));
console.log(path.join(process.cwd(), 'package.json'));
console.log(path.resolve('./', 'package.json'));
console.log(__filename);
console.log(__dirname);

然后,我们在项目 A 的跟目录下执行 node scripts/index.js,结果如下:

-> node scripts/index.js
package.json
/Users/xiaolian/Code/A/package.json
src/index.js
/Users/xiaolian/Code/A/src/index.js
/Users/xiaolian/Code/A/package.json
/Users/xiaolian/Code/A/package.json
/Users/xiaolian/Code/A/scripts/index.js
/Users/xiaolian/Code/A/scripts

品,仔细品,它们有什么区别。

个人而言,一般还是习惯用 path.join(process.cwd(), 'xxx')

File System 模块


// 内置模块,直接使用
const fs = require('fs');

文件系统相关操作的模块,除了 fs 之外,我们还经常用到 fs-extra,后面会介绍。

这个模块在平时的 Node 开发中会被大量使用,这里简单列几个,其它的还是看文档哈:nodejs.org/dist/latest…

fs 模块的 API 默认都是异步回调的形式,如果你想使用同步的方法,有两种解决方法:

  1. 使用 Node 提供的同步 API:xxxSync,也就是在 API 的后面加一个 Sync 后缀,它就是一个同步方法了(具体还是需要查文档哈,是否有提供同步 API)
  2. 包装成一个 Promise 使用

fs.stat(path[, options], callback)

fs.stat() 返回一个文件或者目录的信息。

const fs = require('fs');

fs.stat('a.js', function(err, stats) {
  console.log(stats);
});

其中包含的参数有很多,介绍几个比较常用的:

export interface StatsBase8742468051c85b06f0a0af9e3e506b5c {
  isFile(): boolean;                 // 判断是否是一个文件
  isDirectory(): boolean;            // 判断是否一个目录

  size: T;                           // 大小(字节数)
  atime: Date;                       // 访问时间
  mtime: Date;                       // 上次文件内容修改时间
  ctime: Date;                       // 上次文件状态改变时间
  birthtime: Date;                   // 创建时间
}

一般我们会使用 fs.stat 来取文件的大小,做一些判断逻辑,比如发布的时候可以检测文件大小是否符合规范。在 CLI 中,经常需要获取一个路径下的所有文件,这时候也需要使用 fs.stat 来判断是目录还是文件,如果是目录则继续递归。当然,现在也有更方便的 API 可以完成这个工作。

同步方法

const fs = require('fs');

try {
  const stats = fs.statSync('a.js');
} catch(e) {}

fs.readdir(path[, options], callback)

fs.readdir(path) 获取 path 目录下的文件和目录,返回值为一个包含 filedirectory 的数组。

假设当前目录为:

.
├── a
│   ├── a.js
│   └── b
│       └── b.js
├── index.js
└── package.json

执行以下代码:

const fs = require('fs');

fs.readdir(process.cwd(), function (error, files) {
  if (!error) {
    console.log(files);
  }
});

返回值为:

[ 'a',
  'index.js',
  'package.json' ]

可以看到这里只返回了根目录下的文件和目录,并没有去深度遍历。所以如果需要获取所有文件名,就需要自己实现递归。

同步方法

const fs = require('fs');

try {
  const dirs = fs.readdirSync(process.cwd());
} catch(e) {}

fs.readFile(path[, options], callback)

文件读取的 API,通过 fs.readFile 可以获取指定 path 的文件内容。

入参如下:

  • 第一个参数: 文件路径
  • 第二个参数: 配置对象,包括 encodingflag,也可以直接传如 encoding 字符串
  • 第三个参数: 回调函数

使用方法如下:

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

fs.readFile(path.join(process.cwd(), 'package.json'), 'utf-8', function (
  error,
  content
) {
  if (!error) {
    console.log(content);
  }
});

如果没传 encoding,则其默认值为 null,此时返回的文件内容为 Buffer 格式。

同步方法

const fs = require('fs');

try {
  fs.readFileSync(path.join(process.cwd(), 'package.json'), 'utf-8');
} catch(e) {}

fs.writeFile(file, data[, options], callback)

对应着读文件 readFilefs 也提供了写文件的 API writeFile,接收四个参数:

  • 第一个参数: 待写入的文件路径
  • 第二个参数: 待写入的文件内容
  • 第三个参数: 配置对象,包括 encodingflag,也可以直接传如 encoding 字符串
  • 第三个参数: 回调函数

使用方法如下:

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

fs.writeFile(
  path.join(process.cwd(), 'result.js'),
  'console.log("Hello World")',
  function (error, content) {
    console.log(error);
  }
);

同步方法

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

try {
  fs.writeFileSync(
    path.join(process.cwd(), 'result.js'),
    'console.log("Hello World")',
    'utf-8'
  );
} catch (e) {}

本文主要是总结了一下在开发 Node 时常用的一些 API,后续的文章会带来 Node 常用的一些三方包。

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of Detailed explanation of commonly used APIs of Process, Path and File System modules in Node.js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete