Как запустить сервер node js и открыть нужную html страницу?
Как запустить сервер node js и открыть нужную html страницу, если фронт собирается вебпаком? То есть без сервера я запускаю webpack serve и вижу index.html. А с сервером я запускаю node index.js, но index.hmtl я не вижу.
Ниже привожу код своих небольших файлов. Всё, что они делают, так это server.js парсит json файл, а index.js и index.html выводят и организуют работу с рандомно построенным графиком (библиотека SciChart это про графики).
server.js
const http = require('http');
const fs = require('fs');
const server = http.createServer((request, response) => {
getData(request, response);
});
const PORT = process.env.PORT || 8080;
server.listen(PORT, () => {
console.log(`Server has been started on ${PORT}...`);
});
function getData(req, res) {
fs.readFile('C:\\Users\\User\\Downloads\\jsons\\example№5.json', 'utf-8', (err, jsonString) => {
if (err) {
console.log(err);
} else {
try {
const data = JSON.parse(jsonString);
let values = data.values;
let current = [];
for (let i = 0; i < values.length; i++) {
if (values[i] !== undefined && values[i][1] === 1) {
current.push(values[i][4]);
}
}
res.writeHead(200);
res.end(JSON.stringify(current));
} catch (err) {
console.log('Error parsing JSON', err);
}
}
});
}
index.js
// Main
import {SciChartSurface} from "scichart/Charting/Visuals/SciChartSurface";
import {NumericAxis} from "scichart/Charting/Visuals/Axis/NumericAxis";
import {FastLineRenderableSeries} from "scichart/charting/visuals/RenderableSeries/FastLineRenderableSeries";
import {XyDataSeries} from "scichart/charting/Model/XyDataSeries";
// Zoom
import {MouseWheelZoomModifier} from "scichart/charting/ChartModifiers/MouseWheelZoomModifier";
import {ZoomPanModifier} from "scichart/Charting/ChartModifiers/ZoomPanModifier";
import {RubberBandXyZoomModifier} from "scichart/charting/ChartModifiers/RubberBandXyZoomModifier";
import {ZoomExtentsModifier} from "scichart/charting/ChartModifiers/ZoomExtentsModifier";
async function initSciChart() {
// Main
const { sciChartSurface, wasmContext } = await SciChartSurface.create("scichart-root");
const xAxis = new NumericAxis(wasmContext);
const yAxis = new NumericAxis(wasmContext);
sciChartSurface.xAxes.add(xAxis);
sciChartSurface.yAxes.add(yAxis);
// Zoom
// // Create 100 dataseries, each with 10k points
for (let seriesCount = 0; seriesCount < 100; seriesCount++) {
const xyDataSeries = new XyDataSeries(wasmContext);
const opacity = (1 - ((seriesCount / 120))).toFixed(2);
// Populate with some data
for(let i = 0; i < 10000; i++) {
xyDataSeries.append(i, Math.sin(i* 0.01) * Math.exp(i*(0.00001*(seriesCount+1))));
}
// Add and create a line series with this data to the chart
// Create a line series
const lineSeries = new FastLineRenderableSeries(wasmContext, {
dataSeries: xyDataSeries,
stroke: `rgba(176,196,222,${opacity})`,
strokeThickness:2
});
sciChartSurface.renderableSeries.add(lineSeries);
}
}
initSciChart();
index.html
<html lang="en-us">
<head>
<meta charset="utf-8" />
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Charts</title>
<script async type="text/javascript" src="bundle.js"></script>
<style>
body { font-family: 'Arial'}
</style>
</head>
<body>
<h1>Charts!</h1>
<p>In this example we add simple zoom and pan behaviour. Select the options below to enable different behaviours</p>
<!-- the Div where the SciChartSurface will reside -->
<div id="scichart-root" style="width: 800px; height: 600px;"></div>
<script>
let request = new XMLHttpRequest();
request.open("POST", "/", true);
request.setRequestHeader("Content-Type", "application/json");
request.send();
request.addEventListener("load", function () {
let obj = JSON.parse(request.response);
alert(obj.message);
});
</script>
</body>
</html>
package.json
{
"name": "tutorial1",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack",
"start": "webpack serve"
},
"author": "",
"license": "ISC",
"dependencies": {
"scichart": "^1.4.1607"
},
"devDependencies": {
"copy-webpack-plugin": "^9.0.0",
"webpack": "^5.38.1",
"webpack-cli": "^4.7.0",
"webpack-dev-server": "^3.11.2"
}
}
Сейчас я просто делаю парсинг данных на сервере, передаю их клиенту - в консоле браузера они выводятся, но html страница не открывается.