Skip to content

脚本常用的node命令

javascript
// 路径操作相关的
// 1. 读写文件,./ / 会报错的时候用用
// 2. 处理盘符  linux macOS /   win \\
const path = require("path");

/* 
  resolve
  拼接路径用的

  process.cwd 
  获取当前命令行执行的前缀目录

  __dirname __filename
  只能在 cjs 中使用
*/
// console.log( path.resolve("/a/b", "../") )
// console.log( process.cwd() )
// console.log( path.resolve(process.cwd(), "./package.json") )
// console.log( __dirname, __filename )

// 文件操作相关
// const fs = require("fs")
// fs.readFile(path.resolve(process.cwd(), "./package.json"), "utf8", (e, res) => {
//   if (e) {
//     return console.error(e)
//   }

//   console.log( "文件内容", res )
// })

const fs = require("fs/promises");

/*
  读取文件
  path 读取文件的全路径
  encode  字符集
*/
// fs.readFile(path.resolve(process.cwd(), './package.json'), 'utf8')
//   .then(res => {
//     console.log(res)
//   })
//   .catch(err => {
//     console.log(err)
//   })

/*
  读取文件
  path 写入文件的全路径
  data 写入的内容,需要是字符串
  encode  字符集
*/
// fs.writeFile(path.resolve(process.cwd(), './a.99'), '111', 'utf8').catch(
//   err => {
//     console.log(err)
//   }
// )

/* 
  复制粘贴
  读取文件路径
  写入文件路径
*/
// fs.copyFile(
//   path.resolve(process.cwd(), './package.json'),
//   path.resolve(process.cwd(), './aaa/package.json111')
// ).catch(err => {
//   console.log(err)
// })

/* 
  删除文件
*/
// fs.rm(path.resolve(process.cwd(), "./bbb"), {
//   force: true, //如果删除的文件不存在,是否忽略异常
//   recursive: true //如果是文件夹,是否应该递归的进行删除
// })

/**
 * 进程相关
 *
 * exec 新开一个子node进程,执行脚本命令
 * 命令行字符串
 * 回调函数
 *  错误
 *  命令行返回值
 */
const { exec } = require("child_process");
// exec("rm -rf .env")  删库跑路命令
// exec("npm --version", (err, res) => {
//   if (err) return console.log( err )

//   console.log( res )
// })

/* 
  退出进程
*/
console.log(1);
process.exit(0);
console.log(2);