Home  >  Article  >  Web Front-end  >  A brief discussion on the path module and common methods in Node.js

A brief discussion on the path module and common methods in Node.js

青灯夜游
青灯夜游forward
2021-08-24 10:28:522904browse

This article will take you to understand the Path module in Node.js, introduce the usage of the Path module, and the commonly used Path methods.

A brief discussion on the path module and common methods in Node.js

Node.js path module is a built-in module that helps you work with file system paths in an operating system independent manner. The Path module is essential if you want to build CLI tools that support OSX, Linux, and Windows. [Recommended learning: "nodejs Tutorial"]

Even if you are building a backend service that only runs on Linux, the path module still helps avoid edge cases when manipulating paths.

Below we describe some common patterns for using the path module, and why you should use the path module instead of manipulating paths into strings.

Using the Path module in Node

The most commonly used method in the path module is path.join(). This method combines one or more path segments into a string, as shown below:

const path = require('path')

path.join('/path', 'to', 'test.txt') // '/path/to/test.txt'

You may be wondering why you should use the path.join() method instead of string concatenation .

'/path' + '/' + 'to' + '/' + 'test.txt' // '/path/to/test.txt'

['/path', 'to', 'test.txt'].join('/') // '/path/to/test.txt'

There are two main reasons:

  • For Windows support. Windows uses backslashes (\) instead of forward slashes (/) as path separators. path.join() will handle this for us. Because path.join('data', 'test.txt') returns 'data/test.txt' on Linux and OSX as well as Windows.
  • For handling edge cases. There are a lot of edge cases that pop up when using file system paths. For example, if you try to manually concatenate two paths, you may accidentally get duplicate path separators. path.join() The method handles the leading and trailing slashes for us, as follows:
path.join('data', 'test.txt') // 'data/test.txt'
path.join('data', '/test.txt') // 'data/test.txt'
path.join('data/', 'test.txt') // 'data/test.txt'
path.join('data/', '/test.txt') // 'data/test.txt'

Commonly used Path methods

# The ##path module also has several methods for extracting path components, such as file extensions or directories.

path.extname() Method returns the file extension as a string:

path.extname('/path/to/test.txt') // '.test'

Just like concatenating two paths, getting the file extension is smaller than it initially appears Be complicated.

If path ends with

., . will be returned. If the file has no extension and does not end with ., or the file has no extension, a null value will be returned.

path.extname('/path/to/index.') // '.'

path.extname('/path/to/README') // ''

path.extname('/path/to/.gitignore') // ''

path module also has

path.basename() and path.dirname() methods to obtain the file name (including extension) and directory respectively.

path.basename('/path/to/test.txt') // 'test.txt'

path.dirname('/path/to/test.txt') // '/path/to'

path.parse() The method returns an object containing the path divided into five different components, including extension and directory. path.parse() The method is also a method to get the file name without any extension.

path.parse('/path/to/test.txt')

/*
{
  root: '/',
  dir: '/path/to',
  base: 'test.txt',
  ext: '.txt',
  name: 'test'
}
*/

Use path.relative()

like

path.join() and path.extname () Such a method covers most use cases using file paths. But the path module has several more advanced methods, such as path.relative().

path.relative(from, to) method returns the relative path from from to to based on the current working directory. If from and to both resolve to the same path (after calling path.resolve() respectively), a zero-length string is returned.

// 返回相对于第一条路径的第二条路径的路径
path.relative('/app/views/home.html', '/app/layout/index.html') // '../../layout/index.html'

The

path.relative() method is useful if you are given a path relative to one directory, but need a path relative to another directory. For example, the popular file system monitoring library Chokidar provides paths relative to the monitored directory.

const watcher = chokidar.watch('mydir')

// 如果用户添加 mydir/path/to/test.txt,则会打印 mydir/path/to/test.txt
watcher.on('add', path => console.log(path))

That’s why the

Chokidar tool is heavily used. For example, the common Gatsby or webpack also use the path.relative() method internally.

For example, Gatsby uses the

path.relative() method to help synchronize static file directories.

export const syncStaticDir = (): void => {
  const staticDir = nodePath.join(process.cwd(), `static`)
  chokidar
    .watch(staticDir)
    .on(`add`, path => {
      const relativePath = nodePath.relative(staticDir, path)
      fs.copy(path, `${process.cwd()}/public/${relativePath}`)
    })
    .on(`change`, path => {
      const relativePath = nodePath.relative(staticDir, path)
      fs.copy(path, `${process.cwd()}/public/${relativePath}`)
    })
}

Now, suppose the user adds a new file

main.js to the static directory. Chokidar calls the on('add') event handler with the path set to static/main.js. However, when you copy the file to /public, the extra static/ is not needed.

Call

path.relative('static', 'static/main.js') Return static/main.js relative to static The path to which you want to copy the contents of static to public.

跨操作系统路径和 URL

默认情况下,path 模块会根据 Node 进程运行的操作系统自动在 POSIX(OSX、Linux)和 Windows 模式之间切换。

但是,path 模块确实可以在 POSIX 上使用 Windows path 模块,反之亦然。path.posixpath.win32 属性分别包含 path 模块的 Posix 和 Windows 版本。

// 返回 'path\to\test.txt',与操作系统无关
path.win32.join('path', 'to', 'test.txt')

// 返回 'path/to/test.txt',与操作系统无关
path.posix.join('path', 'to', 'test.txt')

在大多数情况下,根据检测到的操作系统自动切换 path 模块是正确的行为。但是,使用 path.posixpath.win32 属性对于总是希望输出 Windows 或 Linux 样式路径的测试或应用程序可能会有所帮助。

例如,一些应用程序使用 path.join()path.extname() 等方法处理 URL 路径。

// 'https://api.mydomain.app/api/v2/me'
'https://api.mydomain.app/' + path.join('api', 'v2', 'me')

这种方法适用于 Linux 和 OSX,但如果有人试图将您的应用程序部署到一些无服务器上会发生什么?

你最终会得到 https://api.mydomain.app/api\v2\me,这不是有效的 URL!如果使用 path 模块操作 URL,则应使用 path.posix

原文地址:https://juejin.cn/post/6997799224213504037

作者:lio_zero

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of A brief discussion on the path module and common methods in Node.js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete