Question

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.

Was it helpful?

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).

OTHER TIPS

Whitespace is automatically trimmed from the start and end of strings. It won't remove whitespace from the middle of a number, e.g., "12 345" (evaluates to NaN). And if there are any non-numeric characters, you'll receive NaN.

See this question for more information.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top