在 JS 中调用 Node.js 可以通过以下方法实现:使用 require() 函数直接调用 Node.js 模块;使用 Node-API 创建 Node.js 模块并使用 import 导入;使用 Worker 线程在单独线程运行 Node.js 代码;使用 Electron 框架在桌面应用程序中使用 Node.js。
如何在 JS 中调用 Node.js
直接调用
使用 require() 函数,您可以直接在 JS 文件中调用 Node.js 模块。
// example.js const { readFileSync } = require('fs'); const data = readFileSync('file.txt', 'utf-8');
使用 Node-API
Node-API 提供了一组 C++ 函数,允许 JS 代码与 C++ 代码交互。您可以使用 Node-API 创建 Node.js 模块并使用 import 语句将其引入 JS 代码中。
// example.cc (Node.js 模块) extern "C" { void SayHello(); } void SayHello() { printf("Hello from Node.js!"); } // example.js import { SayHello } from './example.js' SayHello();
使用 Worker 线程
Worker 线程允许您在单独的线程中运行 Node.js 代码。这对于执行耗时任务非常有用,而不会阻塞主 JS 线程。
const worker = new Worker('worker.js', { type: 'module' }); worker.postMessage('message'); worker.onmessage = (e) => { console.log(e.data); }; // worker.js import { readFileSync } from 'fs'; onmessage = (e) => { const data = readFileSync('file.txt', 'utf-8'); postMessage(data); };
使用 Electron
Electron 是一个允许您使用 Node.js 构建桌面应用程序的框架。Electron 为在 JS 和 Node.js 之间进行通信提供了专用的 API。
const { app, BrowserWindow, dialog } = require('electron'); const createWindow = () => { const win = new BrowserWindow(); win.webContents.on('did-finish-load', () => { win.webContents.executeJavaScript('console.log("Hello from Node.js!");'); }); win.loadFile('index.html'); }; app.whenReady().then(() => { createWindow(); app.activate(); });
以上就是js如何调用node.js的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号