文件模块

23 阅读1分钟

文件模块fs

yarn init -y    // 初始化
创建index.js并写入内容
node index.js   // 运行index.js
// conmmander.js
yarn add commander    // 安装commander
yarn add inquirer     // 安装inquirer.js

发布到npm

配置package.json

"name" : "myName",    // name必须唯一
"bin": {
    "t" : "cli.js"    // cli.js命令变为t
  },
"files": [
  "cli.js", "db.js", "index.js"    // 或 *.js
],

配置node shebang工具

#!/user/bin/env node

执行chmod +x cli.js // Mac和Linux必须执行 发布到npm

nrm ls  // 查看源
nrm use npm  // 使用npm源
npm adduser  // 登录
npm publish  // 发布

使用myNode

yarn global add node-todo-ljm-1  // 全局安装
// 更新代码操作(每次更新必须更改version)
npm publish    // 更新代码后直接上传
yarn global add node-todo-ljm-1@latest  // 选择版本号安装
t --version    // 查看版本号

代码中加入了version

uTools_1699502404240.png

单元测试--文件模块

  1. 测试模块不能真正的对外部文件有操作,因此需要mock
  2. 规范的单元测试文件,约定俗成单元测试文件为spec.js 或 unit.js
yarn add --dev jest    // 下载jest,并写入测试代码
"scripts": { "test": "jest" },    // package.json
yarn test
afterEach(() => {   // 每运行it就清除
        fs.clearMocks()
    })
  • 读测试

  • 写测试

由于写文件时不能真的写入外部文件,所以把他写入一个变量里

调试

/.idea/
/node_modules/
/.vscode/
  1. vscode配置文件 + 要调试的代码设置红点断电(或代码上一行写debugger) uTools_1699793730886.png

  2. 命令行调试node --inspect-brk cli.js add task 200

curl -v http://localhost:8888       // get请求
curl -v -d "name=lu" http://localhost:8888    // post请求