当前位置: 首页 > news >正文

用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' }}
}

相关文章:

  • 为什么使用Throwable app不崩溃,使用Exception会崩溃
  • AlarmClock4.8.4(官方版)桌面时钟工具软件下载安装教程
  • nacos设置权重进行负载均衡不生效
  • 在 Spring Boot 中实现 WebSockets
  • URP-利用矩阵在Shader中实现物体的平移和缩放
  • 中建海龙MiC模块化建筑赋能“好房子”新范式
  • Linux 权限修改详解:chmod 命令与权限数字的秘密
  • 15.ArkUI Checkbox的介绍和使用
  • 人工智能(AI)对网络管理的影响
  • 增加首屏图片
  • 【Deepseek学习大模型推理】MOONCAKE: A KVCache-centric Architecture实验部分(下)
  • 软件测试入门学习笔记
  • 代码随想录学习笔记---二叉树
  • PCI 总线学习笔记(五)
  • 【华为HCIP | 华为数通工程师】821—多选解析—第十六页
  • 关注心理健康,开启心灵养生之旅
  • OpenCV 图形API(63)图像结构分析和形状描述符------计算图像中非零像素的边界框函数boundingRect()
  • MySQL触法器
  • Golang | 迭代器模式
  • 快速了解redis,个人笔记
  • “70后”通化市委书记孙简已任吉林省政府领导
  • 四川公布一起影视盗版案例:1个网站2人团伙盗售30多万部
  • 山西10岁男孩遭生母和继父殴打遇害,案件庭审延期
  • 著名诗人、中国城市发展研究院原常务副院长吕贵品逝世
  • 基辅响起密集爆炸声,乌方称俄军发动大规模导弹袭击
  • 巴勒斯坦民族权力机构主席:哈马斯必须移交武器