当前位置: 首页 > 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' }}
}
http://www.dtcms.com/a/155674.html

相关文章:

  • 为什么使用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,个人笔记
  • PyTorch深度学习框架60天进阶学习计划 - 第51天:扩散模型原理(二)
  • BT151-ASEMI无人机专用功率器件BT151
  • docker 代理配置冲突问题
  • (Go Gin)基于Go的WEB开发框架,GO Gin是什么?怎么启动?本文给你答案
  • VGA/EDP/HDMI转LVDS,支持1920*1080,1920*1200@120HZ
  • 笔记:记一次使用EasyExcel重写convertToExcelData方法无法读取@ExcelDictFormat注解的问题(已解决)
  • wireshark从HEX转储导入使用方法
  • Uni-App 多端电子合同开源项目介绍
  • React类组件与React Hooks写法对比
  • STM32 I2C总线通信协议