简体   繁体   English

Node.js类作为模块

[英]Node.js classes as modules

I am trying to make my application more object orientated. 我试图使我的应用程序更面向对象。 for this i want to create the following class (object): 为此,我想创建以下类(对象):

in the file Media.js 在文件Media.js中

    //Media object
var Media = function (file, targetDirectory) {
    this.file = file;
    this.targetDir = targetDirectory;
    this.fileName = this.getName();
};

Media.prototype.isVideo = function () {
    return this.file.mimetype.indexOf('video') >= 0;
};
Media.prototype.isAudio = function () {
    return this.file.mimetype.indexOf('audio') >= 0;
};
Media.prototype.getName = function () {
    return this.file.originalname.substr(0, this.file.originalname.indexOf('.'))
};

I wish to use this object in serveral places of my application however im not quite sure how to include it. 我希望在我的应用程序的服务器位置使用此对象,但是我不确定如何将其包括在内。 Also is this a good idea or should i use Modules instead? 这也是一个好主意还是我应该使用Modules代替?

You can export your Media object as follows in Media.js 您可以在Media.js中按如下所示导出Media对象

module.exports = Media;

then simply require Media.js when you need it 然后在需要时只需要Media.js

const Media = require('pathtofile/Media.js')

Media.isAudio(a, b); 

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM