美文网首页Node.jsDeno
Deno 下命令行子进程实操

Deno 下命令行子进程实操

作者: Kenny锅 | 来源:发表于2020-05-17 20:43 被阅读0次

    说白了就是在 subprocess 下执行 shell 命令

    • cmd 表示命令,用逗号来代替 shell 里的空格

    下面就是我用 Deno 重写一遍原来用 shell 来实现打包功能(主要是不会在命令行生成带时间戳的文件名,逃

    import { moment } from 'https://deno.land/x/moment/moment.ts';
    const { run } = Deno;
    
    const timeStamp = moment().format('YYYYMMDD-hhmmss');
    
    const removeOld = async () => {
      const rimraf = run({
        cmd: ['rimraf', 'tool/*.zip'],
      });
      await rimraf.status();
      rimraf.close();
    
      const newFiles = 'dist,.DS_Store,package.json,package-lock.json'.split(',');
      for (const file of newFiles) {
        const filePath = `tool/${file}`;
        const runCmd = run({
          cmd: ['rm', '-rf', filePath],
        });
        await runCmd.status();
        runCmd.close();
      }
    };
    
    const copyNew = async () => {
      const newFiles = 'dist,.npmrc,package.json,package-lock.json'.split(',');
      for (const file of newFiles) {
        const runCmd = run({
          cmd: ['cp', file === 'dist' ? '-Rf' : '-f', file, 'tool'],
        });
        await runCmd.status();
        runCmd.close();
      }
    };
    
    const zip = async () => {
      const runCmd = run({
        cmd: ['zip', '-r', `tool/导出小工具-${timeStamp}.zip`, 'tool'],
      });
      await runCmd.status();
      runCmd.close();
    };
    
    const main = async () => {
      await removeOld();
      await copyNew();
      await zip();
    };
    
    main();
    

    为什么不用 copyFile readFile 之类的内置命令
    答: 这些命令不支持目录的遍历操作,也不支持 *.* 通配符

    API 使用说明:

    相关文章

      网友评论

        本文标题:Deno 下命令行子进程实操

        本文链接:https://www.haomeiwen.com/subject/llzsohtx.html