如何在React Native App中使用Node.js代码 [英] How to use Node.js code in React Native App
问题描述
我有一个Node.js代码,该代码连接到Azure's IoT Hub
并将消息发送到集线器.这是代码:
I have a Node.js code that connects to Azure's IoT Hub
and sends messages to the hub. Here is the code:
'use strict';
var connectionString = 'connectionString';
// Using the Node.js Device SDK for IoT Hub:
// https://github.com/Azure/azure-iot-sdk-node
// The sample connects to a device-specific MQTT endpoint on your IoT Hub.
var Mqtt = require('azure-iot-device-mqtt').Mqtt;
var DeviceClient = require('azure-iot-device').Client
var Message = require('azure-iot-device').Message;
var client = DeviceClient.fromConnectionString(connectionString, Mqtt);
// Create a message and send it to the IoT hub every second
setInterval(function(){
// Simulate telemetry.
var temperature = 20 + (Math.random() * 15);
var message = new Message(JSON.stringify({
temperature: temperature,
humidity: 60 + (Math.random() * 20)
}));
// Add a custom application property to the message.
// An IoT hub can filter on these properties without access to the message body.
message.properties.add('temperatureAlert', (temperature > 30) ? 'true' : 'false');
console.log('Sending message: ' + message.getData());
// Send the message.
client.sendEvent(message, function (err) {
if (err) {
console.error('send error: ' + err.toString());
} else {
console.log('message sent');
}
});
}, 1000);
我有一个带有按钮的React Native应用程序,我想每次按下按钮时使用Node.js文件将消息发送到IoT中心.我如何在我的React Native文件中包含该文件?请帮忙,谢谢.
I have a React Native app that has a button and I want to send a message using the Node.js file to the IoT Hub every time I press the button. How do I include the file within my React Native file? Please help, thanks.
推荐答案
Azure IoT中心设备SDK需要一个Node.js运行时,该运行时在React Native应用程序中不存在.
The Azure IoT Hub Device SDK needs a Node.js runtime, which does not exists within the React Native app.
有一个名为 nodejs-mobile-react-native 的插件React Native引入了Node.js运行时,并允许您与React Native应用程序一起运行Node.js应用程序.
There is a plugin called nodejs-mobile-react-native for React Native that brings in the Node.js runtime and enables you to run Node.js apps alongside your React Native application.
我写了有关该主题的详细博客文章,概述了实现此目标所需的步骤.
I have written a detailed blog post about this topic outlining the steps necessary to achieve this.
这篇关于如何在React Native App中使用Node.js代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!