简体   繁体   中英

How to send realtime file update from node js server (express) to angular js

As a newbie, I am writing a simple application which will monitor a text file in my server and whenever any change happens to the text file I have to send file contents to client.

I am using node.js and angular .

Currently I am considering to use socket.io with express but not sure if it is the correct way.

Need help to find the Correct way.

My sample Server code is below.

var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var fs = require('fs');
var filePath = 'C:\\MyPrograms\\testfile.txt';
var file = fs.readFileSync(filePath);

app.use(express.static(__dirname + '/public'));

io.on('connection', function(socket) {
  console.log('new connection');
});


server.listen(4041, function() {
  console.log('server up and running at 4041 port');});

console.log('Initial File content : ' + file);

fs.watch(filePath, function(event, filename) {
  if(filename){
    file = fs.readFileSync(filePath);
    console.log('File content : ' + file);
    io.emit('filemodified', { message: 'Content Changed' });
    } else{
    console.log('filename not provided')
  }
});

Please also suggest if instead of using socket.io i can use nodemon for this.

If I understood your problem correctly, fs.watch(filePath, function(event, filename) {}); API should work fine.

The only suggestion That I'd like to give you is understand the difference between socket.io and web-sockets .

Socket.io comes up with loads of features which you might not be using in your application.

However, the overhead in using socket.io is you will have to include an additional script on client side to make it work.

web-socket on the other hand is a core feature and you don't have to include any external dependency to make it work.

Obviously web-sockets are not as feature-rich as socket.io, it's is always better to choose one of the options as per the requirement.

I hope this helps :)

Thanks I have done it using socket.io as this will be helpful in my future projects. Don't know why I asked for nodemon as an alternate. Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM