【发布时间】:2016-10-27 10:28:01
【问题描述】:
在 chokidar 模块的帮助下,我正在创建一个文件夹监视程序。我的 Server.js 代码是:
let express = require('express')
let app = express();
let http = require('http').Server(app);
let path = require('path');
let chokidar = require('chokidar');
let io = require('socket.io')(http);
let port = process.env.port || 1337;
let clientPath = path.join(__dirname, 'client');
app.use(express.static(clientPath));
app.get('/', function (req, res) {
res.sendFile(path.join(clientPath, 'HTML1.html'));
});
http.listen(port, function () {
console.log(`listning on ${port}`);
});
let watcher = chokidar.watch(path.join(clientPath, 'images'),
{ ignored: /^\./, persistent: true }
);
watcher
.on('add', function (path) {
console.log('File', path, 'has been added');
io.sockets.on('connection', function (socket) {
socket.emit('imageAddClient', { imagePath: path });
socket.on('imageAddServer', function (data) {
console.log(`${data.imagePath} has been processed at client`);
});
});
})
.on('change', function (path) {
console.log('File', path, 'has been changed');
})
.on('unlink', function (path) {
console.log('File', path, 'has been removed');
})
.on('error', function (error) {
console.error('Error happened', error);
});
在客户端,我创建了 angular factory,以便在添加图像后自动加载页面。我的客户代码是:
var app = angular.module('imageLoaderApp', []);
app.controller('loadController', function ($scope, socket) {
try {
images = [];
socket.on('imageAddClient', function (data) {
let fileName = data.imagePath.substring(data.imagePath.lastIndexOf('\\') + 1);
console.log(fileName);
images.push({ name: fileName, src: fileName });
socket.emit('imageAddServer', { imagePath: fileName });
});
$scope.images = images;
//console.log($scope.images);
}
catch (exception) {
console.log(`Error from loadController ${exception}`);
}
});
app.factory('socket', function ($rootScope) {
var socket = io.connect('http://localhost:1337');
return {
on: function (eventName, callBack) {
socket.on(eventName, function () {
let args = arguments;
$rootScope.$apply(function () {
callBack.apply(socket, args);
});
});
},
emit: function (eventName, data, callBack) {
socket.emit(eventName, data);
}
}
});
但是,来自 io 的“连接”事件仅在一次我启动服务器时触发。后记如果我在文件夹中添加一个图像文件,我可以看到 watcher 事件被触发但 'connection' 事件没有被触发。
我做错了什么?
【问题讨论】:
标签: javascript angularjs node.js socket.io