我的nodejs js文件在CLI nodejs上下文中执行时引发错误“ ReferenceError:未定义”。但是,在nodejs REPL交互式shell中执行“ console.log(require)”将返回有效的函数定义。
$ cat r.js
console.log(require);
$ node
Welcome to Node.js v12.17.0.
Type ".help" for more information.
> console.log(require);
[Function: require] {
resolve: [Function: resolve] { paths: [Function: paths] },
main: undefined,
extensions: [Object: null prototype] {
'.js': [Function],
'.json': [Function],
'.node': [Function]
},
cache: [Object: null prototype] {}
}
undefined
$ node r.js
(node:8341) ExperimentalWarning: The ESM module loader is experimental.
file:///work/testnodejs/r.js:1
console.log(require);
^
ReferenceError: require is not defined
at file:///work/testnodejs/r.js:1:13
在节点的REPL下执行console.log(需要)。>>
> console.log(require); [Function: require] { resolve: [Function: resolve] { paths: [Function: paths] }, main: undefined, extensions: [Object: null prototype] { '.js': [Function], '.json': [Function], '.node': [Function] }, cache: [Object: null prototype] {} } undefined
在CLI nodejs上下文中执行(仅使用一条语句console.log(require);)
node helloWorld.js Function: require] { resolve: [Function: resolve] { paths: [Function: paths] }, main: Module { id: '.', path: '/Applications/node-course', exports: {}, parent: null, filename: '/Applications/node-course/helloWorld.js', loaded: false, children: [], paths: [ '/Applications/node-course/node_modules', '/Applications/node_modules', '/node_modules' ] }, extensions: [Object: null prototype] { '.js': [Function], '.json': [Function], '.node': [Function] }, cache: [Object: null prototype] { '/Applications/node-course/helloWorld.js': Module { id: '.', path: '/Applications/node-course', exports: {}, parent: null, filename: '/Applications/node-course/helloWorld.js', loaded: false, children: [], paths: [Array] } } }
require是Node.js中的内置函数,它提供了最简单的方法来包含存在于单独文件中的模块。参考nodejs.org
只要您已在计算机中全局安装节点并在节点的上下文中执行console.log(require),将打印上述函数定义。
希望这会有所帮助。