Stream the contents of each file using web sockets

2019-03-04 16:12发布

问题:

I am trying to read files of a directory and usin socket i have to render the file name and file data using React.

here is what i have done:

Server :

var files = fs.readdirSync(currentPath);
   for (var i in files) {

        (function(j){

      var currentFile = currentPath + '/' + files[j];
      var fileName = files[j];
      var stats = fs.statSync(currentFile);

      if (stats.isFile()) {
           fs.readFile(currentFile, function (err, data) {

                if (err)
                    throw err;
                if (data){
                    var fileAndData=currentFile+" "+data.toString('utf8')
                    io.emit('file data',fileAndData);


           console.log("file name and file data ***",currentFile+data.toString('utf8'));
                }

            });
           }
     else if (stats.isDirectory()) {
            traverseFileSystem(currentFile);
          }
    }
     )( i );

     }

client : parent component :

class FileData extends Component{
  constructor(props) {
      super(props);
      this.state = {
       filedata:null,
       filename:null,
       data:[]
      }
   }
componentDidMount() {
    socket.on('file data', function(msg){
    this.state.data.push(msg);
    // this.setState({filename:msg})

  }.bind(this));    
}

render(){

return(<div>
    <DataCard data={this.state.data}/>
    </div>);

}
}

ReactDOM.render(
    <FileData/>,document.getElementById('messages')
);

client : child component

constructor(props) {
            super(props);
            this.state={data:this.props.data}
        }

        render(){
            console.log("array",Array.isArray(this.state.data))
            console.log("array length",this.state.data.length)
            console.log("array is ==>",this.state.data)


            return(
                <MuiThemeProvider>

                  </MuiThemeProvider>);
        }

I want display the data and file name and file data using map.But when i am consoling the data recieved in child component Array length is Zero. Here is the

console result : 
array true
array length 0
array is ==> Array[0]0: "/vagrant/assignment/server/data//file 1.txt hello from file 1."1: "/vagrant/assignment/server/data//file 2.txt hello from file 2."length: 2__proto__: Array[0]

Why 3rd console showing 2 data if its length is zero.

回答1:

You can't mutate the state by doing this.state.data.push(msg);

Try

var data = this.state.data;
data.push(msg);
this.setState({data: data});