This is the second day of my participation in Gwen Challenge

File path processing module path

Nodejs provides the path module for file path processing. It smoothes out the differences between operating systems, allowing us to generate and process file paths on any operating system.

The most common method is resolve

Path. resolve is the most common file path handling method, which is used to generate an absolute path. For example, in webpack, we often see path.resolve. An absolute path is generated by combining the current file directory and the passed parameter. This path is usually used with __dirname, for example:

// The execution directory is one layer above the current file
const {resolve} = require('path');
console.log(resolve(__dirname, 'resolve.js')); // /Users/admin/study-every-day/20210609/resolve.js
console.log(resolve('resolve.js')) // /Users/admin/study-every-day/resolve.js
Copy the code

As you can see from the example above, __dirname is the absolute path to the current file directory, and resolve returns a path that does not end with a path separator, which means that we usually use this method to read a file

The path join function join

The difference between JOIN and resolve is that join is only a path connection. The path returned by join is absolute based on the passed parameter. If the passed parameter is absolute, it is an absolute path; if not, it is a common path after joining.

const {join} = require('path');
console.log(join(__dirname, 'join.js')) // /Users/admin/coding/study-every-day/20210609/join.js
console.log(join('usr'.'local')) // usr/local
Copy the code

Gets the relative relationship between the two paths

Path.relative returns the relative relationship between two passed paths, as shown below

const {relative} = require('path');
const from = '/usr/local/project/'
const to = '/usr/local/project/components/'
console.log(relative(from, to)) // components
Copy the code

Check whether the current path isAbsolute isAbsolute

Path. isAbsolute Returns whether the current directory is an absolute path

console.log(isAbsolute(__dirname));  // true
console.log(isAbsolute('join')); // false
Copy the code

Get the current file name basename

Path. basename Obtains the file name of the current file, including the file name extension, as follows:

const {basename} = require('path');
console.log(basename(__dirname + '/basename.js')) // basename.js
Copy the code

Gets the current file suffix extname

Path. extname Obtains the file suffix of the current file, as follows

const {basename, extname} = require('path');
console.log(extname(__dirname + '/basename.js')) // .js
Copy the code

Gets the current system path separator

Path. sep is the current system path separator

conclusion

The above is all the content of today, welcome everyone to like the message, or put forward their own modules to see the content