获取一个文件路径作为全局节点包中的参数 [英] Get a file path as an argument in the global node package
问题描述
我正在尝试创建一个全局节点包,以便在该包的运行目录中执行某些操作.例如,我想使用该节点包 CLI 删除一些文件.命令将是这样的:
I am trying to create a global node package for doing something in the running directory of that package. For example, I want to remove some files with that node package CLI. The command will be something like this:
my-package ./test-file.txt
如何在包节点应用程序中获取 ./test-file.txt
路径作为参数?我认为它应该在论点中,但如果有更好的方法,我将不胜感激.
How can I get the ./test-file.txt
path as an argument in the package node app?
I think it should be in the argument but if there is a better way I will appreciate knowing that.
推荐答案
通常process.argv
用于读取参数.
Typically process.argv
is utilized to read argument(s).
例如;
以下示例将索引
2
处的参数分配给filepath
变量.
The following example assigns the argument at index
2
to afilepath
variable.
const [ , , filepath ] = process.argv;
以下示例将索引 2
中的所有参数作为数组分配给 args
变量.
The following example assigns all arguments from index 2
to the args
variable as an Array.
const [ , , ...args ] = process.argv;
注意:process.argv
在索引 0
和 1
处读取的参数通常是 node.js分别是可执行路径和 JS 文件路径——因此为什么在上述示例中我们跳过它们 解构数组,使用, ,
.
Note: Arguments read by process.argv
at index 0
and 1
are typically the node.js executable path and the JS filepath respectively - hence why in the aforementioned examples we skip over them when destructuring the Array, using , ,
.
基于 OP 的后续评论:
Based on the OP's subsequent comment:
"如何获取该文件的完整路径?用户将向应用程序发送类似 ./test.txt
的内容.如何获取文件的 [绝对] 路径?
"How can I get the full path of that file? the user will send something like
./test.txt
to the application. How can I get the [absolute] path to the file?"
首先,以下假设您正在使用 node.js 构建命令行工具 - 这就是您的问题所暗示的.在这种情况下,请考虑使用 path.resolve()
和传入 process.cwd()
和 filepath
变量.
Firstly, the following assumes you are building a command line tool using node.js - as that is what your question implies. In which case consider utilizing path.resolve()
and pass in process.cwd()
and the filepath
variable.
例如:
cli.js
#! /usr/bin/env node
const { resolve } = require('path');
// 1. Obtain the relative path argument provided via
// the CLI and assign it to the `filepath` variable.
const [ , , filepath ] = process.argv;
// 2. Obtain the absolute path for the given relative
// path and assign it to the `absPath` variable.
const absPath = resolve(process.cwd(), filepath);
然后在全局节点包的 package.json 中,您必须确保已经定义了 bin
属性是这样的:
Then in the package.json for your global node package you must ensure you've defined your bin
property something like this:
package.json
{
...
"bin": {
"my-package": "./cli.js"
},
...
}
参见 npm博客了解更多详情.
See npm blog for further details.
这篇关于获取一个文件路径作为全局节点包中的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!