even

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

1、利用node原生封装一个求文件hash的方法

const { createHash } = require('crypto');
const { createReadStream } = require('fs');

const getFileMd5 = (filePath) => {
  return new Promise((resolve) => {
    const md5sum = createHash('md5');
    const stream = createReadStream(filePath);

    stream.on('data', (chunk) => md5sum.update(chunk));

    stream.on('end', () => resolve(md5sum.digest('hex')));
  });
};

2、用js把版本号转成数值进行计算

/**
 * 把版本号转成指定的数值
 * @param version
 * @returns
 */
export const convertVersionToInt = (version: string): number => {
    const versionArr = version.split('.');

    if (versionArr.length < 1) return -1;

    let int = 0;
    for (let i = 0, len = versionArr.length; i < len; i++) {
        const tempInt = parseInt(versionArr[i], 10) << (10 * (versionArr.length - i - 1));
        int += tempInt;
    }

    return int;
};

 3、封装一个spawn的方法

function commandSpawn(cmd, args, options = {}) {
  return new Promise((resolve, reject) => {
    const res = spawn(cmd, args, {
      stdio: [0, 1, 2],
      ...options,
    })

    let stdout = ''
    let stderr = ''

    res.stdout &&
      res.stdout.on('data', (data) => {
        stdout += data.toString()
      })

    res.stderr &&
      res.stderr.on('data', (data) => {
        stderr += data.toString()
      })

    res.on('close', (code) => {
      if (code !== 0) {
        reject(new Error(`${cmd} process exited with code ${code}: ${stderr}`))
      } else {
        resolve(stdout)
      }
    })

    res.on('error', (err) => {
      reject(err)
    })
  })
}

// 注意:如果需要取得返回的结果,需要把stdio改成pipe

 如果不需要知道结果,可以按下面的来

export const commandSpawn = (cmd: string, args: string[], options: SpawnOptions = {}): Promise<boolean> => {
    return new Promise((resolve, reject) => {
        try {
            const process = spawn(cmd, args, {
                detached: true,
                stdio: 'ignore',
                ...options,
            });
            process.on('error', (error) => {
                reject(error);
            });

            process.unref();
            if (process.pid !== undefined) {
                resolve(true);
            }
        } catch (error) {
            reject(error);
        }
    });
};

 注意:如果是执行shell命令,spawn的第三个参数需要设置为{shell:true}

4、node中利用spawn实现子进程任务以及通信

主进程代码

const { spawn } = require('child_process')

const child = spawn("node", ['second.js'], {
    stdio: [0, 1, 2, 'ipc'],   // 以ipc的形式进行通信,监听消息用message, 发送消息用send
    cwd: process.cwd()
})


let count = 0
child.on('message', (data) => {
    if(data === 'ok') process.exit(0)

    console.log('接收到的信息', data)
    count ++

    if(count >= 5) child.send({action: 'stop'})
})

子进程代码

const handle = setInterval(() => {
  process.send({ msg: 'this is test' });
}, 1000);

process.on('message', (data) => {
  if (data) {
    console.log(data);

    clearInterval(handle);

    process.send('ok'); // 子进程回复主进程的消息
  }
});

 利用node.js调用powershell来获取window的管理员权限, 以下例子是调用管理员权限调用nvm切换版本到16.16.0版本中

const commandToRun = 'powershell.exe';
const commandArgs = [
  '-ExecutionPolicy',
  'Bypass',
  '-NoProfile',
  '-Command',
  `Start-Process -Wait -Verb RunAs nvm -ArgumentList 'use 16.16.0'`
];

const child = spawn(commandToRun, commandArgs, { shell: true });

 

posted on 2023-03-05 23:14  even_blogs  阅读(35)  评论(0编辑  收藏  举报