最近在作一个脚手架的项目,涉及到了一些关于nodeJS端的操做。网上找了不少资源,以及一些设想,都在此处记录下来,做为一种总结。github博客node
命令行指令操做时,须要使用到如下几个包:git
@oclif/command
@oclif/config
@oclif/plugin-help
@oclif/dev-cli
复制代码
首先,建立一个简单的CLI脚本文件run,以下:github
#!/usr/bin/env node
require('@oclif/command').run()
.then(require('@oclif/command/flush'))
.catch(require('@oclif/errors/handle'));
复制代码
而后在package.json中添加配置,以下:npm
{
"bin": { //命令指向的脚本地址
"clitest": "./bin/run"
}
}
复制代码
以后,创建一个link,以下:json
npm link //执行以后,会在命令行中出现clitest
复制代码
而后,逐个创建脚手架命令。例如create命令,以下:bash
const Command = require('@oclif/command');
class CreateCli extends Command.Command {
constructor() {
super(...arguments);
}
async run() {
try {
console.log('create');
} catch(err) {
console.log(err);
}
}
}
CreateCli.description = 'create test';
exports.default = CreateCli;
复制代码
最后,在package.json中指明command地址,以下:cookie
"oclif": {
"commands": "./commands",
"bin": "clitest",
"plugins": [
"@oclif/plugin-help"
]
},
"files": [
"/bin",
"/commands"
],
复制代码
脚手架命令部分构建基本完毕了。以下是执行成功的图片:app
编写脚手架的过程当中,路径问题常常容易出错。下面总结了一些nodeJS中经常会使用到的路径变量:async
__dirname: 指当前执行文件所在目录的完整目录名
__filename: 指当前执行文件的带有完整绝对路径的文件名
process.cwd(): 指当前执行node命令时候的文件夹目录名
./: 指文件所在目录
os.homedir(): 指系统的home目录
复制代码
下面是一些实验的数据结果,以下:函数
const path = require('path');
const os = require('os');
console.log(path.resolve(__dirname));
console.log(path.resolve(__filename));
console.log(process.cwd());
console.log(os.homedir());
console.log(path.basename(__dirname));
console.log(path.basename(__filename));
复制代码
执行结果:
此处使用到的npm是watch。
npm install watch
复制代码
通常使用函数watch.watchTree(root)。在脚手架中,咱们每每须要监听一些文件的改动状况,以下:
watch.watchTree(src, {
filter: (filePath) => {
// 过滤不须要被监听的文件和文件夹
// ...
}
}, (f, curr, prev) => {
if (typeof f == "object" && prev === null && curr === null) {
// Finished walking the tree
} else if (prev === null) {
// f is a new file
} else if (curr.nlink === 0) {
// f was removed
} else {
// f was changed
}
});
复制代码
以后,咱们须要对于新增文件、删除文件和文件改变中做出操做。
此处使用到的npm是request。
npm install request
复制代码
在登陆请求和上传文件的过程当中,咱们须要使用到formData来进行上传,可是nodeJS并没有FormData的对象,因此,这里就要涉及到使用request来进行上传了。
request.post({
url, //请求接口
form: {
userName: username,
password: password
}
}, (err, response: Response, body) => {
// ...
});
复制代码
同理,上传文件时,也能够经过form表单的形式上传上去。可是,通常文件上传的接口都须要登陆,因此须要在带上cookie。
const j = request.jar();
j.setCookie(cookie);
const req = request.post({
url,
jar: j
}, (err, res: Responese, body) => {
// ...
});
const form = req.form();
form.append(fileName, file);
复制代码