我正在尝试用javascript制作一个.smil(.xml)解析器。
但当我想测试它时,node.js只是告诉我:

buffer.js:246
    switch(encoding && encoding.toLowerCase()){
                                ^
TypeError: Object 1 has no method 'toLowerCase'
    at Function.Buffer.isEncoding (buffer.js:246:32)
    at assertEncoding (fs.js:98:27)
    at Object.fsread (fs.js:422:5)
    at gets (/home/pi/SMIL_Parser.js:8:8)
    at read_until (/home/pi/SMIL_Parser.js:28:14)
    at home/pi/SMIL_Parser.js:64:14
    at Object.oncomplete (fs.js:93.15)

gets()确实是我的函数之一:
var io=require('fs');
...
function gets (file){
    var chaine="", cache="", pkmn=0;
    io.read(file, cache, 0, 1, null, function(err, byte, buf){
        if (err || byte===0){return -1;}
        while ((cache!=="\n"))
        {
            chaine=chaine+cache;
            cache="";
            pkmn=io.readSync(file, cache, 0, 1, null);
            if (pkmn===0){return -1;}
        }
    });
}

我只是不知道出了什么问题,它似乎是阅读,但我已经确保得到正确的参数,试图更新node.js,fs和npm。我在google上发现的唯一类似错误是更新问题。
编辑:
添加了完整的错误消息,在此函数读取到:
function read_until(smil, limit){
    var line="";
    do
    {
        line=gets(smil);
        if (line===-1){return -1}
    }while (!(line.search(limit)));
    return 0;
}

是的。
function parse (pathname){
    var smil=0, line="", pkmn=0;
    io.open(pathname, 'r', function (err, fd){
        if (err){return -1;}
        smil=fd;
        pkmn=read_until(smil, "<smil>");
        ...

最佳答案

fs.readtakes a buffer not a string.
将缓存更改为缓冲区。

function gets (file){
    var chaine="", cache=new Buffer(), pkmn=0;
    io.read(file, cache, 0, 1, null, function(err, byte, buf){
        if (err || byte===0){return -1;}
        while ((cache!=="\n"))
        {
            chaine=chaine+cache;
            cache="";
            pkmn=io.readSync(file, cache, 0, 1, null);
            if (pkmn===0){return -1;}
        }
    });
}

查看fs.read code here
如果要将字符串用作“缓冲区”,则必须使用传统接口
传统字符串接口fs.read(fd, length, position, encoding, callback)

07-24 09:49
查看更多