node-system-bridge
Version:
A cross-platform system automation library for Node.js and Electron, written in Rust
84 lines (69 loc) • 2.23 kB
JavaScript
// ESM wrapper for node-system-bridge
import { createRequire } from 'node:module'
import { fileURLToPath } from 'node:url'
import { dirname, join } from 'node:path'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const require = createRequire(import.meta.url)
// 检测平台和架构
const { platform, arch } = process
let nativeBinding = null
let loadError = null
// 根据平台加载对应的 .node 文件
function loadNativeBinding() {
const bindings = {
'darwin-x64': 'node-system-bridge.darwin-x64.node',
'darwin-arm64': 'node-system-bridge.darwin-arm64.node',
'win32-x64': 'node-system-bridge.win32-x64-msvc.node',
'linux-x64': 'node-system-bridge.linux-x64-gnu.node'
}
const key = `${platform}-${arch}`
const bindingFile = bindings[key]
if (!bindingFile) {
throw new Error(`Unsupported platform: ${platform}-${arch}`)
}
// 原始路径(开发环境 / 普通 Node 环境使用)
const bindingPath = join(__dirname, bindingFile)
// Electron 环境下,如果当前位于 app.asar 中,则优先从 app.asar.unpacked 中加载 .node
const isElectron = !!(process.versions && process.versions.electron)
if (isElectron && bindingPath.includes('app.asar')) {
const unpackedPath = bindingPath.replace('app.asar', 'app.asar.unpacked')
try {
return require(unpackedPath)
} catch (e) {
// 如果从 unpacked 目录加载失败,记录错误但继续尝试原始路径
loadError = e
}
}
try {
return require(bindingPath)
} catch (e) {
loadError = e
throw new Error(`Failed to load native binding for ${platform}-${arch}: ${e.message}`)
}
}
// 加载 native 模块
try {
nativeBinding = loadNativeBinding()
} catch (e) {
if (loadError) {
throw loadError
}
throw e
}
// ESM 导出
export const Process = nativeBinding.Process
export const Mouse = nativeBinding.Mouse
export const Keyboard = nativeBinding.Keyboard
export const Clipboard = nativeBinding.Clipboard
export const Window = nativeBinding.Window
export const System = nativeBinding.System
// 默认导出(兼容性)
export default {
Process,
Mouse,
Keyboard,
Clipboard,
Window,
System
}