


Detailed explanation of commonly used APIs of Process, Path and File System modules in Node.js
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.
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.join
The 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 默认都是异步回调的形式,如果你想使用同步的方法,有两种解决方法:
- 使用 Node 提供的同步 API:
xxxSync
,也就是在 API 的后面加一个Sync
后缀,它就是一个同步方法了(具体还是需要查文档哈,是否有提供同步 API) - 包装成一个 Promise 使用
fs.stat(path[, options], callback)
fs.stat()
返回一个文件或者目录的信息。
const fs = require('fs'); fs.stat('a.js', function(err, stats) { console.log(stats); });
其中包含的参数有很多,介绍几个比较常用的:
export interface StatsBase<t> { isFile(): boolean; // 判断是否是一个文件 isDirectory(): boolean; // 判断是否一个目录 size: T; // 大小(字节数) atime: Date; // 访问时间 mtime: Date; // 上次文件内容修改时间 ctime: Date; // 上次文件状态改变时间 birthtime: Date; // 创建时间 }</t>
一般我们会使用 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
目录下的文件和目录,返回值为一个包含 file
和 directory
的数组。
假设当前目录为:
. ├── 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
的文件内容。
入参如下:
- 第一个参数: 文件路径
- 第二个参数: 配置对象,包括
encoding
和flag
,也可以直接传如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)
对应着读文件 readFile
,fs
也提供了写文件的 API writeFile
,接收四个参数:
- 第一个参数: 待写入的文件路径
- 第二个参数: 待写入的文件内容
- 第三个参数: 配置对象,包括
encoding
和flag
,也可以直接传如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!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

WebStorm Mac version
Useful JavaScript development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.