Node.js 中的 Assert 模块

node.jsjavascriptweb developmentfront end technology

assert 模块提供了一系列用于函数断言的不同功能。此模块提供这些函数来验证程序中的不变量。我们可以使用断言进行空值检查或其他不同的检查。断言不会影响任何正在运行的实现。它只检查条件,如果错误不满足,则会抛出错误。

安装 Assert 模块

npm install assert

assert 模块是内置的 Node.js 模块,因此您也可以跳过此步骤。

在函数中导入模块

const assert = require("assert");

示例

const assert = require('assert');
let x = 3;
let y = 21;
assert(x>y);

输出

C:\home
ode>> node assert.js assert.js:339    throw err;    ^ AssertionError [ERR_ASSERTION]: The expression evaluated to a falsy value:    assert(x>y)       at Object. (/home/node/mysql-test/assert.js:6:1)       at Module._compile (internal/modules/cjs/loader.js:778:30)       at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)       at Module.load (internal/modules/cjs/loader.js:653:32)       at tryModuleLoad (internal/modules/cjs/loader.js:593:12)       at Function.Module._load (internal/modules/cjs/loader.js:585:3)       at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)       at startup (internal/bootstrap/node.js:283:19)       at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

示例

让我们再看一个例子。在上面的程序中,我们没有处理错误。我们告诉系统为我们处理该错误。因此,它会打印所有系统日志。在此示例中,我们将使用 try() 和 catch() 块处理任何错误。

const assert = require('assert');

let x = 3;
let y = 21;

try {
   // 检查条件...
   assert(x == y);
}
catch {
   // 如果发生错误,则打印错误
   console.log(
      `${x} is not equal to ${y}`);
}

输出

C:\home
ode>> node assert.js 3 is not equal to 21

相关文章