前言

偶尔会写一些 node 小工具,由于不是经常写忘的很快,特此记录一下一些常用的依赖包之类的;

支持esmodule

修改type属性;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"serve":"node bin/index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"chalk": "^4.1.2",
"execa": "^5.1.1",
"inquirer": "^8.2.0"
}
}

chalk

地址:chalk

美化控制台的输出

1
2
console.log(chalk.blue('Hello world!'))
console.log(chalk.red('hello world!'))

execa

地址:execa
可以开子进程,用来执行一些命令

1
2
3
4
5
6
7
8
const child_process = execa('yarn serve', {
cwd: url.root, // 命令执行的项目地址
shell: true,
stdio: [2, 2, 2]
}).then(res => {
console.log('execa res:', res);
child_process.kill();
});

inquirer

地址:inquirer
控制台输入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import inquirer from 'inquirer'

export default function () {
return inquirer.prompt([
{
type: 'input',
name: 'projectName',
message: 'set project name',
validate(input) {
if (input) return true
return 'Please enter project name'
},
},
{
type: 'list',
name: 'frame',
message: 'please select a frame',
choices: ['vue', 'react'],
validate(input) {
// Declare function as asynchronous, and save the done callback
var done = this.async()
// Do async stuff
setTimeout(function () {
if (typeof input !== 'number') {
// Pass the return value in the done callback
done('You need to select a frame')
return
}
// Pass the return value in the done callback
done(null, true)
}, 3000)
},
},
])
}

__dirname

需要特殊处理

1
2
3
4
5
6
7
8
import { fileURLToPath } from 'url';

const __dirname = fileURLToPath(import.meta.url);

function resolve(dir) {
return path.join(__dirname, dir);
}