【问题标题】:Unable to start node js server when wanted to tail a file想要尾随文件时无法启动节点 js 服务器
【发布时间】:2019-09-02 22:25:32
【问题描述】:

我写了一个非常简单的node js + react js app。目的是尾随文件并发送以响应显示并不断更新它以使用 react-sequence-diagram 生成序列图。 现在我的服务器的index.js 看起来像:

const express = require('express');
const os = require('os');
const fs = require('fs');
const app = express();

// Gives error (option 1): Doesn't work
// const Tail = require('tail-file');
// tail = new Tail('/home/roshan/syslog');
// const mytail = new Tail("/home/roshan/syslog", data => {
//     app.use(express.static('dist'));
//     app.get('/api/getUsername', (req, res) => {
//         res.writeHead(200, {'Content-Type': 'text/plain', 'connection': 'keep-alive'} );
//         res.write(data);
//         res.end();
//     });

// Gives error (option 2): Doesn't work
// Tail = require('tail').Tail;
// tail = new Tail('/home/roshan/syslog');
// var options= {separator: /[\r]{0,1}\n/, fromBeginning: true, fsWatchOptions: {}, follow: true}
//     tail.on("line", function(data) {
//         console.log(data);
//         app.use(express.static('dist'));
//         app.get('/api/getUsername', (req, res) => {
//             res.writeHead(200, {'Content-Type': 'text/plain', 'connection': 'keep-alive'});
//             res.write(data);
//             res.end();
//         });
//     tail.watchEvent.call(tail, "change");
//     tail.on("error", function(error) {
//         console.log('ERROR: ', error);
//         });

// only this works
fs.readFile('/home/roshan/syslog', "utf8",  function(err, data) {
    app.use(express.static('dist'));
    app.get('/api/getUsername', (req, res) => {
        res.writeHead(200, {'Content-Type': 'text/plain', 'connection': 'keep-alive'} );
        res.write(data);
        res.end();
    });


    app.listen(process.env.PORT || 8080, () => console.log(`Listening on port ${process.env.PORT || 8080}!`));
  });

我在webpack.config.js 中关于代理连接的设置

  devServer: {
    port: 9000,
    open: true,
    proxy: {
      '/api/': {
      target: "http://[::1]:8080",
      changeOrigin: true,
      secure: false
      }
    }
  },

而客户端app.js 看起来像这样:

import React, { Component } from 'react';
import './app.css';
import ReactImage from './react.png';
import SequenceDiagram from 'react-sequence-diagram';

export default class App extends Component {
  state = { time:Date.now(), results: ""};

  componentDidMount() {    
    fetch('/api/getUsername')
      .then(res => res.text()
      .then((text) => {
        this.setState({ results: text });
      })
      )
      this.interval = setInterval(() => this.setState({ time: Date.now()}), 5000);
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  render() {

    const options = {
      theme: 'simple'
    };

    const input = this.state.results
    return (
      <div>
    <SequenceDiagram input={input} options={options}/>
      </div>
    );
  }
}

每当我使用选项 1 或 2 时,我都会收到错误消息:

[1]ℹ「wdm」:编译成功。 [1] [HPM] 尝试将请求 /api/getUsername 从 localhost:9000 代理到 http://[::1]:8080 (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors) 时出错

我做错了什么?我以npm run dev 的身份盯着服务器,样板文件取自这里https://github.com/crsandeep/simple-react-full-stack/tree/master/src/server

【问题讨论】:

标签: node.js reactjs


【解决方案1】:

请试试这个,但这不是最好的,你必须使用 websocket 将数据从文件推送到前端应用程序,

 const express = require('express');
 const os = require('os');
 const fs = require('fs');
 const app = express();
 const Tail = require('tail-file');

 let data = ""; 

  app.use(express.static('dist'));
  app.get('/api/getUsername', (req, res) => {
     res.writeHead(200, {'Content-Type': 'text/plain', 'connection': 'keep-alive'} );
     res.write(data);
     res.end();
     //   data= "";  // un comment this line if you don't need old data
 });

  const mytail = new Tail('/home/roshan/syslog', line => {
     data = data + line ; 
  });



app.listen(process.env.PORT || 8080, () => 
  console.log(`Listening on port ${process.env.PORT || 8080}!`));
});

【讨论】:

    猜你喜欢
    • 2017-07-31
    • 2017-08-06
    • 2017-09-11
    • 2013-08-25
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多