问题描述
我在节点js中有2个脚本。一种使用“ http”,另一种使用“ net”。我想将这些脚本一起制作成一个脚本。我的“ http”脚本如下:
import React from 'react';
import { Provider } from 'react-native-paper';
import App from './src';
import { theme } from './src/core/theme';
import { NavigationContainer } from '@react-navigation/native';
import Drawer from './src/components/Drawer';
export default () => {
return (
<NavigationContainer>
<Drawer />
</NavigationContainer>
);
};
'net'脚本:
const http = require('http');
const hostname = 'localhost';
const port = 3000;
const server = http.createServer((req,res) => {
console.log(req.headers);
res.statusCode = 200;
res.end('<html><body><h1>Hello,World!</h1></body></html>');
})
server.listen(port,hostname);
我的目的是在启动“ http”脚本后运行“ net”脚本。
解决方法
将整个net script
包装在导出的函数中:
var net = require('net');
module.exports = () => {
var client = new net.Socket();
client.connect(4352,'x.x.x.x',function() {
console.log('Connected');
client.write('%1POWR 1\r\n');
});
client.on('data',function(data) {
console.log('Received: ' + data);
client.destroy(); // kill client after server's response
});
client.on('close',function() {
console.log('Connection closed');
});
}
在http script
中导入并执行导出的函数:
const http = require('http');
const hostname = 'localhost';
const port = 3000;
require('path/to/net/script')() //Add to anywhere you like
const server = http.createServer((req,res) => {
console.log(req.headers);
res.statusCode = 200;
res.end('<html><body><h1>Hello,World!</h1></body></html>');
})
server.listen(port,hostname);