JavaScript ES6 - console.log 带有模板文字

JavaScript ES6 - console.log with template literal

我正在编写连接到 mongo 数据库的节点脚本。

我注意到打印错误响应因 console.log 语法中的微小变化而有所不同。下面的例子应该更有意义。

#!/usr/bin/env node

const mongoose = require("mongoose");
const config = require("./config");

mongoose.connect(config.dbURI, (err) => {
    if (err) {
        console.log(`${err}`); // First console.log
        console.log(err); // Second console.log
    } else {
        console.log(`Database connection successful`)
    }
});

第一个 console.log

的示例输出
MongoError: Authentication failed.

第二个示例输出 console.log

{ MongoError: Authentication failed.
    at Function.MongoError.create (/Users/sigo/Sources/crypto-change/node_modules/mongodb-core/lib/error.js:31:11)
    at /Users/sigo/Sources/crypto-change/node_modules/mongodb-core/lib/connection/pool.js:489:72
    at authenticateStragglers (/Users/sigo/Sources/crypto-change/node_modules/mongodb-core/lib/connection/pool.js:435:16)
    at Connection.messageHandler (/Users/sigo/Sources/crypto-change/node_modules/mongodb-core/lib/connection/pool.js:469:5)
    at Socket.<anonymous> (/Users/sigo/Sources/crypto-change/node_modules/mongodb-core/lib/connection/connection.js:321:22)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:191:7)
    at readableAddChunk (_stream_readable.js:178:18)
    at Socket.Readable.push (_stream_readable.js:136:10)
    at TCP.onread (net.js:563:20)
  name: 'MongoError',
  message: 'Authentication failed.',
  ok: 0,
  code: 18,
  errmsg: 'Authentication failed.' }

这种差异从何而来?

${err}(或 '' + err)将使用字符串插入 err 对象,这也会改变您的 Error object into a string - which is equivalent to calling err.toString()。然而,直接记录 err 会将其作为对象传递到控制台并以该方式显示。

这叫做 "implicit coercion" - 如果您想了解更多关于这个主题的信息,我强烈建议您阅读 You Don't Know JS: Types & Grammar (Chapter 4: Coercion) 以深入了解。

通过插入模板字符串,err object is cast to a string, using its own .toString method that is inherited from Error.prototype.toString。代码相当于

console.log(String(err));
console.log(err.toString());

当将 err 对象直接传递给 console.log method, it uses node's inspect function 时,代码等同于

console.log(util.inspect(err));