最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to check the number in Node.js - Stack Overflow

programmeradmin1浏览0评论

Here is the code for testing if the given variable is an integer and it's value is greater than zero.

let test_port = "443";
if(!(Number.isInteger(test_port)) || (Number(test_port) <= 0)){
  throw new Error(`Invalid port: "${test_port}"`);
}

But when running this js in VS Code, here is the error:

C:\Program Files\nodejs\node.exe .\app.js
Process exited with code 1
Uncaught Error Error: Invalid port: "443"
    at <anonymous> (d:\test\app.js:3:9)
    at <anonymous> (<node_internals>/internal/modules/cjs/loader:1554:14)
    at <anonymous> (<node_internals>/internal/modules/cjs/loader:1706:10)
    at <anonymous> (<node_internals>/internal/modules/cjs/loader:1289:32)
    at <anonymous> (<node_internals>/internal/modules/cjs/loader:1108:12)
    at traceSync (<node_internals>/diagnostics_channel:322:14)
    at wrapModuleLoad (<node_internals>/internal/modules/cjs/loader:220:24)
    at executeUserEntryPoint (<node_internals>/internal/modules/run_main:170:5)
    at <anonymous> (<node_internals>/internal/main/run_main_module:36:49)
app.js:3
No debugger available, can not send 'variables'

What's wrong in my code and how to fix?

Here is the code for testing if the given variable is an integer and it's value is greater than zero.

let test_port = "443";
if(!(Number.isInteger(test_port)) || (Number(test_port) <= 0)){
  throw new Error(`Invalid port: "${test_port}"`);
}

But when running this js in VS Code, here is the error:

C:\Program Files\nodejs\node.exe .\app.js
Process exited with code 1
Uncaught Error Error: Invalid port: "443"
    at <anonymous> (d:\test\app.js:3:9)
    at <anonymous> (<node_internals>/internal/modules/cjs/loader:1554:14)
    at <anonymous> (<node_internals>/internal/modules/cjs/loader:1706:10)
    at <anonymous> (<node_internals>/internal/modules/cjs/loader:1289:32)
    at <anonymous> (<node_internals>/internal/modules/cjs/loader:1108:12)
    at traceSync (<node_internals>/diagnostics_channel:322:14)
    at wrapModuleLoad (<node_internals>/internal/modules/cjs/loader:220:24)
    at executeUserEntryPoint (<node_internals>/internal/modules/run_main:170:5)
    at <anonymous> (<node_internals>/internal/main/run_main_module:36:49)
app.js:3
No debugger available, can not send 'variables'

What's wrong in my code and how to fix?

Share Improve this question edited Mar 19 at 5:32 Phil 165k25 gold badges262 silver badges267 bronze badges asked Mar 19 at 4:25 stackbizstackbiz 1,4722 gold badges13 silver badges30 bronze badges 1
  • 1 The error occurs because Number.isInteger(test_port) returns false when test_port is a string, causing the check to fail before properly converting it to a number. You have to first convert it to a number, then check with isInteger() like: let test_port = "443"; let port_number = Number(test_port); if (!Number.isInteger(port_number) || port_number <= 0) {throw new Error("Invalid port:", test_port) ;} – Yash Commented Mar 19 at 4:42
Add a comment  | 

3 Answers 3

Reset to default 2

In the first condition : Number.isInteger checks if a value is an integer but it expects a number not a string. Therefore in this case when you pass "443" to Number.isInteger it returns false and --> !(false) becomes true.

So first convert the string to number using Number(test_port) and then pass check if it is a Integer or Not.

let test_port = "443"; 
if(!(Number.isInteger(Number(test_port))) || (Number(test_port) <= 0)) { 
throw new Error(`Invalid port: "${test_port}"`); 
}

As @yash and @rushil stated, the conditional failed because Number.isInteger evaluates to false given a string as input.

To check a port number's validity correctly, you could still use the Number constructor, but if you could get any type as input, you'll want to make sure you don't get a TypeError from some of the possible input types.

Assuming you want to be as strict as possible (which is probably overkill), I'd parse to a Number first:

const MAX_PORT = (1 << 16) - 1; // you might as well check the upper bound, too.

/**
 * @param {any} maybePort
 * @returns {number} the numeric value of the input, or `-1` if the type is impossible to convert to a port number.
 */
function parsePort(maybePort) {
  if(typeof maybePort === "number" || typeof maybePort === "string") {
    return Number(maybePort); // could be float or int
  } else if (typeof maybePort === "bigint" && maybePort <= BigInt(MAX_PORT)) {
    /* checking bounds here because `asUIntN` will truncate, 
     * so a number with MSBs above 2^16 plus a valid port number
     * could "mistakenly" parse to a valid port number.
     */
    return BigInt.asUIntN(16, maybePort);
  } else {
    /*
       [ "undefined", 
         "object", 
         "function", 
         "symbol",
         "boolean" 
       ].includes(typeof maybePort) === true
     */
    return -1;  
  }
}

If you know what input types are possible, it's a little simpler and you can probably get away with just the Number constructor instead of handling bigint and all the others.

/**
 * @param {any} port
 * @returns {boolean} `true` if the given value is a valid port number, and `false` otherwise.
 */
function isValidPortNumber(maybePort) {
  let port = parsePort(maybePort);
  
  /* 
   * I inverted your conditional because it's easier to read (IMHO).
   * It shows the reader what inputs you *are* looking for, instead of what you're rejecting:
   */

   // A valid port number is...
   return Number.isInteger(port) && // an integer...
          port > 0 && // that is positive...
          port <= MAX_PORT; // and below 2^16.
}

// ...in action
if (!isValidPortNumber(test_port) {
  throw new Error(`Invalid port: "${test_port}"`);
}

If you don't need to be as strict, just prune the parsePort function until you've removed all the impossible states.

If only string or number types are possible as inputs, then you could probably just use Number.parseInt if you're ok with floats being truncated.

Try making the test_port variable an integer either you can directly pass on the integer or convert it to an integer and then pass in if

let test_port = 443
if(!(Number.isInteger(test_port)) || (Number(test_port) <= 0)){
  throw new Error(`Invalid port: "${test_port}"`);
}else{
    console.log("this works");
}
发布评论

评论列表(0)

  1. 暂无评论