NodeJs require('./file.js')问题 [英] NodeJs require('./file.js') issues

查看:159
本文介绍了NodeJs require('./file.js')问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一些问题,包括要在NodeJs项目中执行的文件.

I am having issues including files to execute in my NodeJs project.

我在同一目录中有两个文件:

I have two files in the same directory:

a.js

var test = "Hello World";

b.js

require('./a.js');
console.log(test);

我用node b.js执行b.js并得到错误ReferenceError: test is not defined.

I execute b.js with node b.js and get the error ReferenceError: test is not defined.

我已经浏览了文档 http://nodejs.org/api/modules.html#modules_file_modules

我想念什么?预先感谢.

What am I missing? Thanks in advance.

推荐答案

更改 a.js 以导出变量:

exports.test = "Hello World";

并将require('./a.js')的返回值分配给变量:

and assign the return value of require('./a.js') to a variable:

var a = require('./a.js');
console.log(a.test);

您经常会看到并可能使用的另一种模式是为 a.js 中的module.exports对象分配某些内容(对象,函数),如下所示:

Another pattern you will often see and probably use is to assign something (an object, function) to the module.exports object in a.js, like so:

module.exports = { big: "string" };

这篇关于NodeJs require('./file.js')问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆