简体   繁体   English

如何编写可在Node.JS应用程序中全局使用的扩展方法?

[英]How do I write extension methods that can be used globally in my Node.JS application?

Take for example this "StartsWith" extension: 以这个“ StartsWith”扩展为例:

if (typeof String.prototype.startsWith != 'function') {
    String.prototype.startsWith = function (str) {
        return this.slice(0, str.length) == str;
    };
}

If I was writing a web app, I would stick that code in an ExtensionMethods.js page that I imported on a web page within my site. 如果我正在编写Web应用程序,则应将该代码粘贴到我在站点内的网页上导入的ExtensionMethods.js页面中。

But what about the case of using this on the server with Node.js? 但是,如何在带有Node.js的服务器上使用它呢?

Thanks! 谢谢!

Since String is globally available, it can be placed in any file that gets required. 由于String是全局可用的,因此可以将其放在需要的任何文件中。 When a file gets required, it gets executed. 需要文件时,将执行该文件。

You don't even need to export anything. 您甚至不需要导出任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 Node.js 制作应用程序,它可以分隔所有具有相同扩展名的文件? - How can i make an application using Node.js, which can separate all the files with same extension? 如何将某些Node.js文件放置在Node.js应用程序根文件夹之外? - How can I place some of my Node.js files outside of my Node.js application root folder? 如何将 Node.js 库转换为可在浏览器中使用的库? - How do I convert a Node.js library into something that can be used in the browser? 我可以在Windows Phone 8应用程序中使用Node.js吗? - Can I use Node.js into my windows phone 8 application? 如何在服务器上全局安装 Node.js 命令行脚本? - How do I globally install a Node.js command-line script on the server? 如何使用 node.js 中的本机承诺在全局范围内处理异常? - How do I handle exceptions globally with native promises in node.js? node.js:如何在我的用户模型上编写“查找或创建”静态方法? - node.js: How can I write a “find or create” static method on my user model? Node.js-如何为应用程序编写插件? - Node.js - How to write plugins for application? 如何写入Node.js Connect / Express记录器? - How do I write to the Node.js Connect/Express logger? 如何为node.js编写以下代码? - How do I write the following code for node.js?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM