程序开发 · 2023年7月9日

js如何调用node.js

在 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的详细内容,更多请关注GTHOST其它相关文章!