监视文件和监视文件更改

时间:2020-02-28 18:49:33

标签: javascript node.js

我正在尝试在日志文件更改时读取并发出更改(此部分有效) 问题是我得到一个错误:

(节点:7088)UnhandledPromiseRejectionWarning:错误:EBUSY:资源繁忙或锁定,打开“ ./temp.log” 在Object.openSync(fs.js:457:3) 在新的LineByLine(C:\ Users \ Server \ Documents \ rconMinecraft \ node_modules \ n-readlines \ readlines.js:23:26) 在myLineReader(C:\ Users \ Server \ Documents \ rconMinecraft \ node_modules \ text-file-diff \ index.js:22:15) 在TextFileDiff.diff(C:\ Users \ Server \ Documents \ rconMinecraft \ node_modules \ text-file-diff \ index.js:63:25) 在Diff(C:\ Users \ Server \ Documents \ rconMinecraft \ app.js:56:7) 更改时(C:\ Users \ Server \ Documents \ rconMinecraft \ app.js:40:3) 在FSWatcher。 (C:\ Users \ Server \ Documents \ rconMinecraft \ app.js:32:7) 在FSWatcher.emit(events.js:321:20) 在FSWatcher.emitWithAll(C:\ Users \ Server \ Documents \ rconMinecraft \ node_modules \ chokidar \ index.js:521:8) 在FSWatcher._emit(C:\ Users \ Server \ Documents \ rconMinecraft \ node_modules \ chokidar \ index.js:613:10) (节点:7088)UnhandledPromiseRejectionWarning:未处理的承诺拒绝。该错误是由于在没有catch块的情况下抛出异步函数而产生的,或者是由于 未使用.catch()处理。要在未处理的承诺拒绝时终止节点进程,请使用CLI标志--unhandled-rejections=strict(请参见https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode)。 (拒绝ID:1) (节点:7088)[DEP0018] DeprecationWarning:已弃用未处理的承诺拒绝。将来,未处理的承诺拒绝将以非零退出代码终止Node.js进程。

我现在出现此错误是因为文件“ ./temp.log”已打开。我正在寻找代码的替代方案,但没有找到。

我的代码:

const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
const express = require('express');
const fs = require('fs');
var chokidar = require('chokidar');
app.use('/public', express.static('public'));
app.get('/', function(req, res) {
    res.sendFile(__dirname + '/views/index.html');
});
var watcher = null;
var _Socket = null;
var path = 'C:/Users/Server/Downloads/Serv/logs/latest.log';
io.sockets.on('connection', function(socket) {
    _Socket = socket;
});

WatchFile();
http.listen(80, function() {
    console.log('listening on *:80');
});

function WatchFile() {
    watcher = chokidar.watch(path, {
        persistent: false
    });
    watcher
        .on('change', path => {
            Change();
        })
}

function Change() {
    fs.copyFile(path, './temp.log', (err) => {
        console.log('this is a test');
    });
    Diff();
}

function Diff() {
    var TextFileDiff = require('text-file-diff');
    var d = new TextFileDiff();
    d.on('compared', (line1, line2, compareResult, lineReader1, lineReader2) => { /*console.log(line1 + " ////// " + line2);*/ });

    d.on('-', line => {
        console.log('File 1 : ' + line);
    });

    d.on('+', line => {
        console.log('File 2 : ' + line);
        _Socket.emit('message', line);
    });
    d.diff(path, './temp.log');

}

0 个答案:

没有答案