全局作用域与局部作用域


默认求值器提供对全局作用域中存在的任何变量的访问。 可以通过将变量分配给与每个 REPLServer 关联的 context 对象来显式地向 REPL 公开变量:

const repl = require('node:repl');
const msg = 'message';

repl.start('> ').context.m = msg;

context 对象中的属性在 REPL 中显示为本地:

$ node repl_test.js
> m
'message'

默认情况下上下文属性不是只读的。 要指定只读的全局变量,则必须使用 Object.defineProperty() 定义上下文属性:

const repl = require('node:repl');
const msg = 'message';

const r = repl.start('> ');
Object.defineProperty(r.context, 'm', {
  configurable: false,
  enumerable: true,
  value: msg,
});

The default evaluator provides access to any variables that exist in the global scope. It is possible to expose a variable to the REPL explicitly by assigning it to the context object associated with each REPLServer:

const repl = require('node:repl');
const msg = 'message';

repl.start('> ').context.m = msg;

Properties in the context object appear as local within the REPL:

$ node repl_test.js
> m
'message'

Context properties are not read-only by default. To specify read-only globals, context properties must be defined using Object.defineProperty():

const repl = require('node:repl');
const msg = 'message';

const r = repl.start('> ');
Object.defineProperty(r.context, 'm', {
  configurable: false,
  enumerable: true,
  value: msg,
});