Search code examples
javascriptnode.jsnumberslinefeed

JavaScript: Intended behavior of Number()


I'm currently reading string integers from files and passing them to functions. Since most files have a trailing line feed, I was wondering about the behavior of Number().

To get the max_pid variable from a RHEL kernel file, I'm using an asynchronous read.

var options = {
  encoding: 'utf8'
};

fs.readFile('/proc/sys/kernel/pid_max', options, function (err, data) {
  var max_pid = Number(data);

  // or trim the string first
  var max_pid = Number(data.trim());
});

The variable data for my system returned the string '32768\n', and using Number() on that string strips the line feed. Is this the intended behavior of Number(), or should I be using str.trim() on the variable before passing it to Number()?

I ask this for reasons of consistency across environments, as well as proper use of functions.


Solution

  • According to Section 9.3.1 of the ECMAScript specification, conversion of a string to a number will automatically strip leading and trailing white space. I'd be shocked if there was a JavaScript engine that did not conform to this part of the spec. The call to trim() is unnecessary (but harmless).