Node.js";无法读取属性';长度';未定义的

Node.js";无法读取属性';长度';未定义的,node.js,socket.io,Node.js,Socket.io,我有一个node.js应用程序(使用socket.io),用于监视生产环境中对网络配置所做的更改。它监视spool目录中的新文件,然后将信息推送到web客户端。当我尝试运行它时,我得到“错误:无法读取未定义的属性‘length’”。任何帮助都将不胜感激 #!/usr/bin/env node // Runtime configuration const SPOOLDIR = process.env['HOME'] + "/spool"; // Where to collect f

我有一个node.js应用程序(使用socket.io),用于监视生产环境中对网络配置所做的更改。它监视spool目录中的新文件,然后将信息推送到web客户端。当我尝试运行它时,我得到“错误:无法读取未定义的属性‘length’”。任何帮助都将不胜感激

#!/usr/bin/env node

// Runtime configuration
const SPOOLDIR = process.env['HOME'] + "/spool";        // Where to collect files
const INTERVAL = 5000;                          // How often to scan
const GRACE = 2000;                             // Minimum age of file before processing

// Dependency modules
const fs = require("fs");
const os = require("os");
const util = require("util");
const app = require('http').createServer(handler)
const io = require('socket.io')(app);

// Global variables:
// - File cache: stat structures by filename
var CACHE={};

// Mini C STDIO  printf/fprintf routines :)
//
const STDOUT=1;
const STDERR=2;
const fprintf = function(fd, fmt) {
    utilfmt_args = Array.prototype.slice.call(arguments, 1);
    var str = util.format.apply(null, utilfmt_args);
    fs.writeSync(fd, str);
}
const printf = function() {
    Array.prototype.unshift.call(arguments, STDOUT);
    fprintf.apply(null, arguments);
}


const startFileScan = function() {
    fs.readdir(SPOOLDIR, processFileResults);
}

const processFileResults = function(err, files) {
    fprintf(STDERR, "processFileResult: %d file(s) found in %s\n", files.length, SPOOLDIR);
    if (err!=undefined) {
        fprintf(STDERR, "Can't read spool directory %s: %s\n", SPOOLDIR, err.code);
        return;
    }

    // Expire any items from the cache that are no longer present
    for (var f in CACHE) {
        if (files.indexOf(f)==-1) {
//          fprintf(STDERR, "Removing file %s from cache\n", f);
            delete CACHE[f];
        }
    }

    // Check any files that are there for modifications, processing them if so
    var currentFile = undefined;
        const doStat = function(err, stats) {
        if (err) {
            fprintf(STDERR, "Error stat()ing %s: %s\n", currentFile, err.code);
        } else {
            if (currentFile!==undefined) {
//              fprintf(STDERR, "Checking file %s with mtime %s against cache\n", currentFile, stats.mtime);
                if (!(currentFile in CACHE) || !(CACHE[currentFile].getTime()==stats.mtime.getTime())) {
                    if (stats.mtime.getTime() + GRACE < Date.now()) {
//                      fprintf(STDERR, "  Updating cache for file %s with mtime %s\n", currentFile, stats.mtime);
                        CACHE[currentFile]=stats.mtime;
//                      fprintf(STDERR, "  File %s has been modified longer than %d ms ago: scheduling for processing\n", currentFile, GRACE);
                        process.nextTick(outputDiffReport, currentFile, CACHE[currentFile]);
                }
            }           
        }
        currentFile = files.pop();
        if (currentFile===undefined) {
//          fprintf(STDERR, "File scan completed: re-scheduling next scan\n");
            process.nextTick(function() { setTimeout(startFileScan, INTERVAL); });
        } else {
            fs.stat(SPOOLDIR + "/" + currentFile, doStat);                      
        }
    };
    process.nextTick(doStat);
}

// App library routines
//
    const outputDiffReport = function(filename, mtime) {
//  fprintf(STDERR, "Processing file %s\n", filename);
    var data="";
    try {
        data = fs.readFileSync(SPOOLDIR + "/" + filename, { encoding: "utf8" });
    } catch(err) {
        fprintf(STDERR, "Can't read incoming filename %s: %s\n", filename, err.code);
    }
    content = data.split(/\n/).filter(function(x) { return x.match(/^[+\-#\[]/); }).join("\n"); 
//  content = data.split(/\n/).filter(function(x) { return ! x.match(/^\s*$/); }).join("\n");   

    io.emit('update', { 'content':  content,
                        'mtime':    mtime.toISOString(),
                        'file':     filename
                    });

fs.unlink(SPOOLDIR + "/" + filename, function() {});
}


// HTTP bootstrap handler routine. Serves out the client HTML
function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }
    res.writeHead(200);
    res.end(data);
  });
}

process.on('uncaughtException', function(err) {
  console.log("ERROR: ", err.message);
  process.exit(1);
});

app.listen(8080);

process.nextTick(startFileScan);
#/usr/bin/env节点
//运行时配置
const SPOOLDIR=process.env['HOME']+“/spool”;//在哪里收集文件
常数间隔=5000;//多久扫描一次
常数GRACE=2000;//处理前文件的最短期限
//依赖模块
常数fs=要求(“fs”);
常数os=要求(“os”);
const util=require(“util”);
const app=require('http')。createServer(处理程序)
常量io=require('socket.io')(应用程序);
//全局变量:
//-文件缓存:按文件名统计结构
var CACHE={};
//迷你C标准打印F/fprintf例程:)
//
常数STDOUT=1;
常数STDERR=2;
常数fprintf=函数(fd,fmt){
utilfmt_args=Array.prototype.slice.call(参数,1);
var str=util.format.apply(null,utilfmt_参数);
fs.writeSync(fd,str);
}
常量printf=函数(){
Array.prototype.unshift.call(参数,STDOUT);
fprintf.apply(null,参数);
}
常量startFileScan=函数(){
fs.readdir(SPOOLDIR,processFileResults);
}
const processFileResults=函数(错误,文件){
fprintf(STDERR,“processFileResult:%d个在%s中找到的文件\n”,files.length,SPOOLDIR);
如果(错误!=未定义){
fprintf(STDERR,“无法读取假脱机目录%s:%s\n”,假脱机目录,错误代码);
返回;
}
//使缓存中不再存在的所有项过期
for(缓存中的变量f){
if(files.indexOf(f)=-1){
//fprintf(STDERR,“从缓存中删除文件%s\n”,f);
删除缓存[f];
}
}
//检查存在的任何文件是否有修改,如果有,则进行处理
var currentFile=未定义;
const doStat=函数(err,stats){
如果(错误){
fprintf(STDERR,“错误统计()正在%s:%s\n”,当前文件,错误代码);
}否则{
如果(currentFile!==未定义){
//fprintf(STDERR,“用mtime%s对照缓存检查文件%s\n”,currentFile,stats.mtime);
如果(!(缓存中的currentFile)| |!(缓存[currentFile].getTime()==stats.mtime.getTime()){
if(stats.mtime.getTime()+GRACE
当调用
processFileResults
时,它要么作为第一个参数获取错误,要么将成功并将
null
作为第一个参数,将文件作为第二个参数

在尝试访问
文件之前,您应该检查错误并进行处理。此外,检查错误是否
未定义
,在语义上没有意义,因为它只能是
null
或错误

const processFileResults = function(err, files) {
    if (err) {
        fprintf(STDERR, "Can't read spool directory %s: %s\n", SPOOLDIR, err.code);
        return;
    }
    fprintf(STDERR, "processFileResult: %d file(s) found in %s\n", files.length, SPOOLDIR);
}

原来是spool目录的权限问题。我为运行该程序而创建的用户没有对该目录的读取权限。

似乎没有将任何文件传递给processFileResults()函数,所以它是未定义的。@WillyB还要补充一点,您是否考虑过使用诸如
chokidar
?之类的软件包。根据对您所做操作的描述,您似乎只需要一个文件观察者来告诉您何时发生文件更改/添加。如果您最终是这样做的,那么使用它将使您的代码不那么混乱sing,而且效率更高。我还没听说过chokidar,但如果它让事情变得更简单,我会研究它。为什么是junos automation标记?你能删除相同的吗?因为它正在查找从juniper事件选项发送的文件。但会删除标记。