Error converting String to Integer type in Nodejs

Asked

Viewed 130 times

0

in Nodejs I am trying to check the value of a variable of type String, but for some reason nothing is working. Example:

var aaa = "0";  // Eu recebo essa variável como string (não dá para mudar o tipo)

console.log(typeof(aaa));   // String
console.log(Number(aaa));   // NaN   ===> Não deveria ser número 0?
console.log(parseInt(aaa)); // NaN   ===> Não deveria ser número 0?

// Isso sempre dá FALSE
aaa = "1";
if (aaa)
    console.log('true');
else
    console.log('false');

// Isso sempre dá FALSE também
aaa = "1";
if (Number(aaa))
    console.log('true');
else
    console.log('false');

What am I missing?

REAL CODE:

  <head>
    <title>TESTE</title>
    <link rel="stylesheet" href="/stylesheets/style.css">
    <link rel="stylesheet" href="/stylesheets/bootstrap.min.css">
    <script src="/socket.io/socket.io.js"> </script>
    <script>
        var socket = io.connect();

        function changeState(state) {
            if (state == 1) {
                socket.emit('changeState', '{"state":1}');
                document.getElementById("outputStatus").innerHTML = "Status: ON";
            } else {
                socket.emit('changeState', '{"state":0}');
                document.getElementById("outputStatus").innerHTML = "Status: OFF";
            }
        }


        socket.on('sensorsUpdate', function (data) {
            var reading = JSON.parse(data);
            document.getElementById("IO_opened").innerHTML = reading.IO_opened;
            document.getElementById("IO_closed").innerHTML = reading.IO_closed;

            if (reading.IO_opened) {
                console.log('ABRIR');
                document.getElementById("IO_opened").className = "exibe";
                document.getElementById("IO_closed").className = "n_exibe";
            } else if (reading.IO_closed) {
                console.log('FECHAR');
                document.getElementById("IO_opened").className = "n_exibe";
                document.getElementById("IO_closed").className = "exibe";
            } else {
                console.log('Open = ' + reading.IO_opened + ' Close = ' + reading.IO_closed);
                document.getElementById("IO_opened").className = "n_exibe";
                document.getElementById("IO_closed").className = "n_exibe";
            }
        });
    </script>
  </head>

It never enters these "if (Reading.IO_". It only enters the last "Else". This javascript code is written in a separate file is inserted directly on the page through a view made in PUG/Jade, through a include:

  head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
    link(rel='stylesheet', href='/stylesheets/bootstrap.min.css')
    script(src='/socket.io/socket.io.js') 
    include ../public/javascripts/sensorStatus.js   //<<<<<====== Include do javascript
  body
  • 2

    You are running the code as? I have tested it here and nothing that you said is happening has happened. See: https://repl.it/JdOc/0

  • Yeah... by simulating I also got the same result as you. Let me give you more details: what happens is that I mount my javascript in Nodejs and publish this javascript code in a View made with PUG/Jade. So far so good, considering that the code arrives identical on the page you will be running. Only when handling such a variable of the string type as I showed, it does not present the same results. It is as if the functions Number() and parseint() interpreted invalid values...

  • How do you publish the JS code in the view? You can add this to the question (the final code generated)?

  • 1

    That’s the real code that’s giving trouble?

  • You can put here the result of console.log(typeof aaa, aaa.length, aaa);?

  • @Andersoncarloswoss edited the text of the question to answer his question. Sergio the log of what you requested appears in real code like this: Typeof Io_opened = string Typeof Io_closed = string.

  • Lacked a ) at last if.

  • I’ve corrected... by also adding real code information @Sergio requested: Number(Reading.Io_closed) = Nan Number(Reading.Io_closed) = Nan

  • "I have already corrected" what I mean is that I added ")". But the code still has a problem that I do not know what is...

Show 4 more comments

1 answer

0


I figured out where the mistake was.

// Eu estava fazendo isso ERRADO!!
var j = {
    "IO_opened": '"' + ioOp + '"',
    "IO_closed": '"' + ioCl + '"'
}

// CORRIGIDO: Agora funciona
var j = {
    "IO_opened": ioOp,
    "IO_closed": ioCl
}

// Esses valores são enviados para a página dessa forma e o JS trata por meio dos "ifs".
s.emit("sensorsUpdate", JSON.stringify(j));

At first I was doing it wrong and instead of IO_opened/IO_closed receive "0" or "1", they received ""0"" or ""1"", with two quotes, which resulted in Number(IO_opened) = NaN in the conversion there in the JS.

This JSON was in another file.... It’s a lot of information for a beginner in Nodejs and JS... I’m very much stuck to the pattern of other languages. Thank you all!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.