前言
使用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' }}
}