开发者

Reading a File and String Equality Problem

I want the following following node.js program to read a file and print out "Login failed." if the text in the file is "Login failed." however the "if (data == "Login failed.") {" line fails to return true and the program prints out "Login succeeded." I'm using "CentOS release 5.5 (Final)" Linux distribution. Any idea as to what's up? Thanks!

BASEPATH = '/home/wz3chen/node/';

fs.readFile(BASEPATH  + 'node.js/' +  "loginLog",  function (err, data) {
    console.log("DATA:" + data);
    if (data == "Login failed.")开发者_如何学Go {
        console.log('Login failed.');
    } else {
        console.log('Login succeeded.');
    }
});


The "data" variable passed to your callback is of type Buffer, which apparently doesn't cast to a string when comparing to a string. You also probably have a newline at the end of your file, so trim it. Try this instead:

if (data.toString().trim() == 'Login failed.') {
  // ...

[Edit]

As @Jim Schubert mentions in his comment, the data argument will be a String if you specify the character encoding in your call to readFile, so you could also do this:

fs.readFile(filename, 'utf8', function(err, data) {
  if (data.trim() == 'Login failed.') {
    // ...


One-line text files in Linux usually end in a new line.

It's not clear whether you're including fs, so here is the code that works for me:

var fs = require('fs'),
    BASEPATH = '/home/jim/bin/';

fs.readFile(BASEPATH  + "loginLog", function (err, data) {
    if (err) throw err;
    console.log("DATA:" + data);

    if (data == "Login failed.\n") {
            console.log('Login failed.');
    } else {
            console.log('Login succeeded.');
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜