In the daily use of Node development, will use some file system, path operation and other basic API, here to sort out, easy to understand and direct use.

Here only introduce the most commonly used ones, not all of them, want to see a more complete, directly look at the official document OK.

Try to cut the crap and code.

The Process module

We’ll start with the Process module, which provides global environment information about the current Node process. Is used in later APIS.

// Built-in module for direct use
const process = require('process');
Copy the code

process.cwd()

This is a function that returns the directory in which the Node process is currently executing. Example of a common scenario:

A Node module A is released via NPM and is used in project B. Process.cwd () can be used to obtain the path of project B when A needs to manipulate files under project B.

const cwd = process.cwd(); / / output: / Users/xiaolian/Code/node - API - test
Copy the code

process.argv

When an endpoint executes a command through Node, process.argv is used to retrieve the command line arguments passed in, and the return value is an array:

  • 0: Node path
  • 1: the path of the JS file to be executed.
  • 2 to n: actual parameters of the command **

So, we simply start fetching from process.argv[2]. It is usually used like this:

const args = process.argv.slice(2);
Copy the code

Get the parameters we want directly.

process.env

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

We typically mount variables on process.env to identify the current environment. For example, the most common distinction between development and production is process.env.node_env. VUE_CLI_DEBUG is also commonly seen in vuE-CLI source code to indicate whether it is currently in DEBUG mode.

DefinePlugin, a webpack plugin, is often used to inject different global variables to execute different build processes and replace process.env.xxx with specific values in code. DeadCode is removed during Terser compression to optimize code size.

process.platform

This is not used much, return the current system information, enumeration value as follows:

console.log(process.platform);

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

The Path module

// Built-in module for direct use
const path = require('path');
Copy the code

This module is used for almost path-related operations in Node.

Here are five of the most common:

path.join(… paths)

Path. join is used to join multiple incoming paths into a complete path.

const dPath = path.join('template'.'aaa'.'bbb'.'ccc'.'d.js');
/ / output: the template/aaa/surprised BBB/CCC/jeter s
Copy the code

For 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');
/ / output: / Users/xiaolian/Code/node - API - the test/package. Json
Copy the code

Path. join can be passed to any path, for example:

['package.json'.'README.md'].forEach(fileName= > {
  const templateFilePath = path.join(process.cwd(), 'template', fileName);
  console.log(templateFilePath);
});
/ / output: / Users/xiaolian/Code/node - API - the test/template/package. Json
/ / output: / Users/xiaolian/Code/node - API - the test/template/README. Md
Copy the code

path.resolve(… paths)

The difference between path.resovle and path.join is that it concatenates multiple paths passed in and the current execution path into a complete absolute path.

Suppose I now have index.js in the scripts directory, and THEN I run node scripts/index.js in the root directory, which looks like this:

const dPath = path.resolve('aaa'.'bbb'.'ccc'.'d.js');
/ / output: / Users/xiaolian/Code/node - API - test surprised/aaa/BBB/CCC/jeter s
Copy the code

Path.resolve (processs.cwd(), ”))./

path.basename(path[, ext])

Path. basename Returns the last pathname of the specified path. The second argument ext is optional, indicating the file extension. Such as:

console.log(path.basename('scripts/index.js'));  // index.js
console.log(path.basename('scripts/index.js'.'.js'));  // Match to.js, return index
console.log(path.basename('scripts/index.js'.'.json'));  // No match is found, return index.js
Copy the code

path.dirname(path)

Basename returns the path before the last pathname of the specified path. Such as:

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

path.extname(path)

Returns the file extension (including the decimal point.) that specified the last pathname of path, corresponding to path.basename. . Such as:

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

contrast

Finally, compare the differences between the various path-related apis.

The directory structure for project A is as follows:

├ ─ ─ scripts │ └ ─ ─ index. The js ├ ─ ─ the SRC │ └ ─ ─ index. The js ├ ─ ─ package. The json ├ ─ ─ the README, mdCopy the code

The code for scripts/index.js is as follows:

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);
Copy the code

Then we execute Node scripts/index.js in the same directory as project A and the result is as follows:

-> 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
Copy the code

Taste, taste carefully, what’s the difference.

Personally, path.join(process.cwd(), ‘XXX ‘) is the preferred option.

The File System module

// Built-in module for direct use
const fs = require('fs');
Copy the code

In addition to FS, we often use fs-extra for file system-related operations, which will be introduced later.

This module is widely used in Node development. Here are a few of them, and the rest are in the documentation: nodejs.org/dist/latest…

Fs module apis are all asynchronous callbacks by default. If you want to use synchronous methods, there are two solutions:

  1. Using Node’s synchronization API:xxxSync, which is to add one after the APISyncSuffix, which is a synchronization method (please check the documentation for details)
  2. Use it wrapped as a Promise

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

Fs.stat () returns information about a file or directory.

const fs = require('fs');

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

There are many parameters in it. Here are some commonly used ones:

export interface StatsBase<T> {
  isFile(): boolean;                 // Check if it is a file
  isDirectory(): boolean;            // Check if it is a directory

  size: T;                           // Size (bytes)
  atime: Date;                       // Access time
  mtime: Date;                       // The last time the file contents were modified
  ctime: Date;                       // The last time the file state changed
  birthtime: Date;                   // Create time
}
Copy the code

We usually use fs.stat to determine the size of the file and do some logic, such as checking whether the file size meets the specification when publishing. On the CLI, you often need to obtain all files in a path. In this case, you also need to use fs.stat to determine whether it is a directory or a file. If it is a directory, you continue recursion. Of course, there are now more convenient apis that can do the job.

Synchronized methods

const fs = require('fs');

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

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

Fs.readdir (path) Retrieves files and directories under the path directory and returns an array containing file and directory.

Assume the current directory is:

. ├ ─ ─ a │ ├ ─ ─ a. s │ └ ─ ─ b │ └ ─ ─ b.j s ├ ─ ─ index. The js └ ─ ─ package. The jsonCopy the code

Execute the following code:

const fs = require('fs');

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

The return value is:

[ 'a'.'index.js'.'package.json' ]
Copy the code

You can see that only the files and directories in the root directory are returned, and no deep traversal is done. So if you want to get all the filenames, you need to implement your own recursion.

Synchronized methods

const fs = require('fs');

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

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

File reading API, fs.readFile can obtain the specified path of the file content.

The entry parameters are as follows:

  • The first parameter: the file path
  • The second parameter: configures the object, includingencodingflag, you can also directly pass such asencodingstring
  • The third argument: the callback function

The usage method is as follows:

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); }});Copy the code

If encoding is not passed, the default value is null, in which case the file content is returned in Buffer format.

Synchronized methods

const fs = require('fs');

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

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

Fs also provides a writeFile API that accepts four parameters:

  • The first parameter: the path to the file to be written
  • Second parameter: the contents of the file to be written
  • Third parameter: configuration object, includingencodingflag, you can also directly pass such asencodingstring
  • The third argument: the callback function

The usage method is as follows:

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); });Copy the code

Synchronized methods

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) {}
Copy the code

This article summarizes some of the apis commonly used in Node development, and subsequent articles will bring up some of the tripartite packages commonly used in Node.


More articles welcome to pay attention to the public number “front end trial”, get front end selected articles.