javascript - 在具有 Express JS 的 Node 应用程序中,如何包含并运行单独的 JS 文件?

标签 javascript node.js express web-applications

我有一个 JavaScript 文件,其中包含一些获取 RSS 提要并将内容保存在数据库中的函数。我最初让 HTML 页面调用它,但我希望这个文件始终在后端运行(从 RSS 源获取更新并将其保存到数据库)。

我的问题是,如何在我的应用程序中附加并运行这个单独的 javascript?我认为它看起来像这样:

在 app.js 中:

var RSSReader = require('./public/javascripts/RSSReader.js');
RSSReader.SomeFunction();

但这不起作用。另外,我的 app.js 中声明的变量在 RSSReader.js 中是否可用?

谢谢。

最佳答案

how can I attach and run this separate javascript within my app?

您显示的 app.js 代码应该可以正常工作。关键是你必须将 RSSReader.js 文件制作成一个模块,导出它想要公开的函数:

因此,在 RSSReader.js 内部,您将拥有如下内容:

module.exports = {
    someFunction: function() {
        // code here
    },
    someOtherFunction: function() {
        // code here
    }
};

然后,在您的其他文件中,您可以加载该模块并像以前一样使用它:

var RSSReader = require('./public/javascripts/RSSReader.js');
RSSReader.someFunction();
RssReader.someOtherFunction();

node.js 模块的文档是 here .

Also, would variables declared in my app.js be available in RSSReader.js?

不,除非您将 app.js 变量显式声明为 global 对象的属性,否则它们不会。从 app.js 共享到另一个模块的常见 Node.js 约定是,为 RSSReader.js 模块创建一个初始化方法(您可以将其称为 init),然后向其传递它需要的任何上下文(通常是一个带有某些属性的对象)来自 app.js,RSSReader.js 模块可以存储该上下文以供其使用。

因此,如果您想将 app.js 中的一些变量共享到 RSSReader.js,您可以通过 .init() 方法共享它们,如下所示:

RSSReader.js

var data;
module.exports = {
    init: function(options) {
        data = options;
    },
    someFunction: function() {
        // code here can access the data variable
    },
    someOtherFunction: function() {
        // code here can access the data variable
    }
};

app.js

var RSSReader = require('./public/javascripts/RSSReader.js');
RSSReader.init({express: express, db: db});
RSSReader.someFunction();
RssReader.someOtherFunction();

关于javascript - 在具有 Express JS 的 Node 应用程序中,如何包含并运行单独的 JS 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30293103/

相关文章:

node.js - Sequelize.Model 不存在

reactjs - 使用 Express 服务 REACT 组件不起作用(仅呈现 html 文件)

javascript - 使用 Three.js 和 Fresnel Shader 可视化网格所有面的问题

node.js - Mongoose $text 字段错误

javascript - 为 JavaScript 寻找好的物理/数学/算法学习资源

node.js - 无法使用 create-react-app 生成项目

javascript - 在 JavaScript 项目中将 NODE_ENV 与多个环境一起使用

javascript - 如何在javascript中基于字符串数组创建嵌套数组?

javascript - 单击后如何禁用 JavaScript 功能?

javascript - 隐藏在 li 标签中的 div