This is the 18th day of my participation in the August Genwen Challenge.More challenges in August
Translated from: shapeshed.com/writing-cro…
One of the main advantages of NodeJS is that it can operate across platforms, and with minimal effort, our code can run on Windows, Linux, and OSX.
The path module provides the tools we need to smooth out the differences between Windows and Linux, OSX for short). If you concatenate strings yourself, you can easily have problems in this area. For example:
path.join('foo'.'bar')
// 'foo/bar' on Linux, OSX
// 'foo\ bar' on Windows
Copy the code
path.resolve
Function: Traverses the file system
Path. resolve allows you to move around the file system while maintaining platform compatibility. You can think of it as a series of CD commands that output a single path.
path.resolve('.. / '.'/.. / '.'.. / ')
/ / '/ home' in Linux
/ / / Users in OSX
/ / 'C: \ \ Users' in Windows
path.resolve('foo'.'bar')
// '/Users/xxx/foo/bar' OSX
Copy the code
path.normalize
Creates a reliable path
If you find yourself doing something like this
let filePath = '/home/george/.. /folder/code';
Copy the code
You should use path.normalize to help you display the correct path on different platforms
var filePath = path.normalize('/home/george/.. /folder/code');
// '/home/folder/code'
Copy the code
The main things this method does are
- Canonical directory dividers
- Apply the current directory to the relative path
- Calculate the relative path in the path (.) And parent directory (..)
- Adjustment formulation character
path.join
Effect: Merge folder names
As we saw earlier, if we use string concatenation, concatenation paths, it can be a problem on different platforms.
If you want to merge paths, use path.join to normalize the results
path.join('foo'.'.. '.'bar'.'baz/foo');
// 'bar/baz/foo' linux、OSX
// 'bar\\baz\\foo' windows
Copy the code
path.basename
Function: Returns the last part of the path
The first argument is the path path, and the second argument is the extension, which is case-sensitive when matched
path.basename('/foo/bar/index.html')
// 'index.html'
path.basename('/foo/bar/index.html'.'.html')
// 'index'
path.basename('/foo/bar/index.HTML'.'.html')
// 'index.HTML'
Copy the code
path.dirname
Function: Returns the directory name of the path
path.dirname('/foo/bar/baz/asdf/quux');
// '/foo/bar/baz/asdf'
Copy the code
path.extname
Function: returns the extension of the path, matching the rule as the last period in the last section (.) To the end of the last character
path.extname('index.html');
// '.html'
path.extname('index');
/ /"
path.extname('.index');
/ /"
Copy the code
The above is a simple use of the path module. Please like and comment ~