节点:控制台测试正在产生类型错误:控制台不是构造函数

问题描述 投票:0回答:1

我已经知道如何在控制台上使用全局实现,但我想使用 Node.js Console 模块。下面的代码是从教程中复制的。 (https://nodejs.dev/en/api/v19/console/

import Console from 'node:console'; //when using modules
or
const { Console } = require('node:console'); //when using straight js


const output = fs.createWriteStream('./stdout.log');
const errorOutput = fs.createWriteStream('./stderr.log');
// Custom simple logger
const logger = new Console({ stdout: output, stderr: errorOutput });
// use it like console
const count = 5;
logger.log('count: %d', count);
// In stdout.log: count 5

但是我收到以下错误

const logger = new Console({ stdout: output, stderr: errorOutput });
               ^

TypeError: Console is not a constructor

我使用的是 Node.js v19.8.1 我已经尝试过模块和直接js。我可以使控制台的全局实现工作,但不是这个。我做错了什么? 谢谢你

node.js console
1个回答
0
投票

使用

console.log(Console)

我找到了可用的方法

Object [console] {
  log: [Function: log],
  warn: [Function: warn],
  dir: [Function: dir],
  time: [Function: time],
  timeEnd: [Function: timeEnd],
  timeLog: [Function: timeLog],
  trace: [Function: trace],
  assert: [Function: assert],
  clear: [Function: clear],
  count: [Function: count],
  countReset: [Function: countReset],
  group: [Function: group],
  groupEnd: [Function: groupEnd],
  table: [Function: table],
  debug: [Function: debug],
  info: [Function: info],
  dirxml: [Function: dirxml],
  error: [Function: error],
  groupCollapsed: [Function: groupCollapsed],
  Console: [Function: Console],
  profile: [Function: profile],
  profileEnd: [Function: profileEnd],
  timeStamp: [Function: timeStamp],
  context: [Function: context]
}

所以这有效

// use it like console
const count = 5;
Console.log('count: %d', count);
// In stdout.log: count 5
© www.soinside.com 2019 - 2024. All rights reserved.