用node打开一个网页
前言
使用node打开网页,要求跨平台
方案
使用子进程来用命令行打开网页链接就可以了,需要注意的是Mac系统使用的是open
命令,Windows系统使用的是start
命令,Linux等系统使用xdg-open
命令。针对不同的操作系统使用不同的命令。
封装子进程命令
将子进程中的exec命令用promisify封装,以返回一个promise
// utils
import util from 'node:util';
import * as child_process from 'child_process';
export const exec = util.promisify(child_process.exec);
封装不同平台的命令
// utils
export const getCommand = (winCommand: string, linuxCommand: string, macCommand: string): string => {if (process.platform === 'win32') {return winCommand;} else if (process.platform === 'darwin') {return macCommand;} else if (process.platform === 'linux') {return linuxCommand;} else {logger.error('Unsupported platform');return '';}
};
根据调用值返回相应的结果
import { exec, getCommand } from '../../utils'
import logger from '../../logger'export const openUrl = async (url: string): Promise<object> => {try {const command = getCommand('start ' + url, 'xdg-open ' + url, 'open ' + url);if (!command) {return { code: 1, msg: 'Unsupported platform' }}await exec(command)return { code: 0, msg: 'Open url success' }} catch (e) {logger.error(`Error open url: ${(e as Error).message}`);return { code: 1, msg: 'Error while open url' }}
}