preface

Before, I used path related content many times when doing webpack configuration. Recently, when I was writing a project, I needed to upload a file to the function of Ali Cloud OSS, and the local server also needed to keep a file backup. Many times used the file path related content and Node core API path module, so the system to learn about, sort out this article.

Koala is dedicated to sharing the complete Node.js technology stack, from JavaScript to Node.js, to back-end database. Wish you become an excellent senior Node.js engineer. [Programmer growth refers to north] Author, Github blog open source project github.com/koala-codin…

Path classification in node

Node in the path points 5 classes, roughly dirname, filename, process. The CWD (),. /,.. / which dirname, filename, process. CWD () an absolute path

Each category is explained by code:

The file directory structure is as follows:

Code pra/ -node core API/ -fs.js-path.jsCopy the code

The code in path.js

const path = require('path');
console.log(__dirname);
console.log(__filename);
console.log(process.cwd());
console.log(path.resolve('/'));
Copy the code

Run the node node core API/path.js command in code pra. You can see the following result:

Koala /Desktop/ programmer growth refers to north/code PRA /node core API/ koala/Desktop/ programmer growth refers to north/code PRA /node core API/ koala/Desktop/ programmer growth refers to north/code PRA /koala/Desktop/ programmer growth refers to north/code PRACopy the code

Then we can run this file, Node path.js, in the node core API directory, as follows:

/koala/Desktop/ programmer growth refers to north/code pra/node core API/ koala/Desktop/ programmer growth refers to north/code pra/node core API/path.js Koala /Desktop/ programmer growth refers to north/code PRA /node core API /koala/Desktop/ programmer growth refers to north/code PRA /node core APICopy the code

Comparing the output, the tentative conclusion is

  • __dirname: Always returns the absolute path of the js folder being executed
  • __filename: Always returns the absolute path of the js being executed
  • Process.cwd (): always returns the absolute path to the folder where the Node command was run
  • ./: As with process.cwd(), return the absolute path to the folder where the node command is located

We added this to path.js. We added this to path.js

exports.A = 1;
Copy the code

Failed to readFile path directly from readFile.

fs.readFile('./path.js'.function(err,data){});Copy the code

Fs.js = fs.js = fs.js

const test = require('./path.js');
console.log(test)
Copy the code

Run node core API/fs.js under pra/ directory.

{ A: 1 }
Copy the code

Then the correct conclusion about./ is this:

Used in require(), it has the same effect as __dirname and does not change depending on the directory in which the script is launched. In other cases, it has the same effect as process.cwd(), which is relative to the directory in which the script is launched.

Summary of path knowledge:

  • __dirname: Gets the full directory name of the directory where the current execution file resides
  • __filename: Gets the file name with the full absolute path to the current execution file
  • process.cwd(): Gets the name of the folder where the node command is currently executed
  • . /: Do not use require,. /withprocess.cwd()As well, userequireTime, with__dirnameThe same

Use relative paths (./,..) only when require(). /), all other places use the absolute path, as follows:

// In the current directory
 path.dirname(__filename) + '/path.js'; 
// In an adjacent directory
 path.resolve(__dirname, '.. /regx/regx.js');
Copy the code

path

Explained the path in front of the comparison, the next talk alone the path the module, the module which are frequently used in many places, so, for us to grasp him, more beneficial to the development of our future, every time see webpack configuration file to check about what, this API is very affect our efficiency

This is the API website :nodejs.org/api/path.ht…

Personally, I don’t think it is necessary to master all the apis in the official website. The following will explain some common apis that I often use, or as a front-end development engineer, I often use in the configuration of Webpack and other projects.

path.normalize

For example

const path = require('path');

console.log(path.normalize('/koala/Desktop// programmer growth refers to north // code pra/.. '));
Copy the code

The result after specification

/koala/Desktop/ programmer growth refers to north/code PRACopy the code

Role summary

Normalize paths, normalize paths that are not normalized.

path.join

For example

const path = require('path');
console.log(path.join('src'.'task.js'));

const path = require('path');
console.log(path.join(' '));
Copy the code

The result of the transformation

src/task.js
.
Copy the code

Role summary

path.join([…paths])

  1. The argument passed in is a path fragment of the string, which can be one or more
  2. It returns a concatenated path, but it normalizes the path differently depending on the platform. For example,UnixSystem is/.WindowsSystem is\Then you will see different results on both systems.
  3. If the path string returned is zero length, it will return one.Represents the current folder.
  4. If any of the parameters passed in are not strings, an error is reported

path.parse

For example

const path = require('path');
console.log(path.parse('/koala/Desktop/ programmer growth refers to north/code PRA/Node core API'));
Copy the code

The results

{ root: '/'.dir: '/koala/Desktop/ Programmer growth refers to north/code PRA '.base: 'the node core API.ext: ' '.name: 'the node core API 
}
Copy the code

Role summary

It returns an object, so let’s familiarize ourselves with some nouns:

  1. Root: indicates the root directory
  2. Dir: indicates the folder where the file resides
  3. Base: indicates the entire file
  4. Name: indicates the file name
  5. Ext: indicates the suffix of the file

path.basename

For example

const path = require('path');
console.log(path.basename('/koala/Desktop/ programmer growth refers to north/code PRA/Node core API'));
console.log(path.basename('/koala/Desktop/ programmer growth refers to north/code pra/node core API/path.js'.'.js'));
Copy the code

The results

Basename = basename; basename = basename; basename = basename;

Node core API PathCopy the code

Role summary

Basename takes two arguments, the first path and the second (optional) ext. When the second argument is entered, the result is printed without the suffix

path.dirname

For example

const path = require('path');
console.log(path.dirname('/koala/Desktop/ programmer growth refers to north/code PRA/Node core API'));
Copy the code

The results

/koala/Desktop/ programmer growth refers to north/code PRACopy the code

Role summary

Returns the full directory address of the file

path.extname

For example

const path = require('path');
path.extname('index.html');
path.extname('index.coffee.md');
path.extname('index.');
path.extname('index');
path.extname('.index');
Copy the code

The results

.html
.md
.
' '
' '
Copy the code

Role summary

It returns the suffix name, but the last two cases return “, notice that.

path.resolve

For example

const path = require('path');
console.log(path.resolve('/foo/bar'.'/bar/faa'.'.. '.'a/.. /c'));
Copy the code

The output

/bar/c
Copy the code

Role summary

path.resolve([…paths])

Path. resolve is the result of running the CD path command from left to right to get the absolute path/filename. However, the resolve operation is different from the CD operation. The resolve path may not exist, and the last entry may be a file. The procedure for CD is as follows

cd /foo/bar/    // This is the first step, and the current position is /foo/bar/
cd /bar/faa     // This is the second step, which is different from the first step, it is entered from /, that is, the root directory, now is /bar/faa
cd ..       // Step 3: Exit from faa, now at /barcd a/.. /c// Step 4: enter a, then enter c, the final position is /bar/c
Copy the code

path.relative

For example

const path = require('path');

console.log(path.relative('/data/orandea/test/aaa'.'/data/orandea/impl/bbb'));

console.log(path.relative('/data/demo'.'/data/demo'));

console.log(path.relative('/data/demo'.' '));
Copy the code

The results

. /.. /impl/bbb"". /.. /koala/Desktop/ programmer growth refers to north/code PRA/Node core APICopy the code

Role summary

path.relative(from, to)

Description: Relative path from from path to to path.

Boundary:

  • If from and to point to the same path, an empty string is returned.
  • If either from or to is empty, return to the current working path.

conclusion

So much for this article on paths, the basics are important, both to save development time and to reduce errors.

Today share so much, if you are interested in sharing the content, you can pay attention to the public account “programmer growth refers to north”, or join the technical exchange group, we discuss together.

Advanced technology route