【问题标题】:How to import js file in nodejs (in cloud9)如何在nodejs中导入js文件(在cloud9中)
【发布时间】:2016-02-02 17:37:16
【问题描述】:

这是一个基本问题,但我正在努力寻找答案。我正在尝试将一个 js 文件(位于此处:http://eloquentjavascript.net/code/ancestry.js)导入我的 Cloud9 Nodejs IDE,但我不知道该怎么做。

我已成功将文件导入到我的库中。但是,我不清楚如何处理文件底部添加的代码:

// `require(./path/to/ancestry.js)` will get you the array.
if (typeof module != "undefined" && module.exports)
  module.exports = ANCESTRY_FILE;

我尝试将其添加到 server.js 文件中,但没有成功。

提前致谢, 乔什

【问题讨论】:

  • 您是否尝试按原样保存文件,而是在同一目录中的另一个 JS 文件中调用它,使用 var ancestry = require('./ancestry');

标签: javascript node.js import


【解决方案1】:

底部的代码通常是检查CommonJS是否启用(基本上是Node.js还是浏览器)。只要你在一个文件夹中有祖先文件,在同一个文件夹中创建另一个文件,例如:list-ancenstry.js 并写入它:

var ancestry = require("./ancestry"); 
console.log(ancestry) //Logs the array

【讨论】:

  • 您的建议奏效了。但是,我无法在即时窗口(Javascript REPL)中运行代码。以下给我一个 ReferenceError: var ancestry = JSON.parse(ANCESTRY_FILE)
  • 否,使用require 运行它。确保您阅读了 Node.js 中的模块导入。顺便说一句,你的设置是什么?这听起来不像是通用的 Node.js 设置。
  • 如果我输入 'var ancestry = require("./ancestry");'在即时窗口中,我得到“ReferenceError:require is not defined”。就我的设置而言,恐怕我不知道如何回答这个问题。这对我来说是新的。您在寻找什么信息?
  • 如果 require 未定义,您的节点设置似乎需要一些调整。
猜你喜欢
  • 2019-06-16
  • 2020-07-02
  • 2019-01-31
  • 2021-06-02
  • 1970-01-01
  • 1970-01-01
  • 2022-06-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多