简体   繁体   English

如何使javascript库在节点js中工作以进行服务器端操作

[英]how to make a javascript library working in node js for server side operations

I am trying to create a library for a project, its like this: 我正在尝试为项目创建一个库,如下所示:

module.exports = Diary;
function Diary() {

    someFunction = function( message ) {
        console.log(message)
    }

    function D() {
        return new D._Section;
    }

    D.about = {
        version: 1.0
    };

    D.toString = function () {
        return  "Diary "+ D.about.version;
    };

    var Section = function () {
        this.Pages = []
    }

    D._Section = Section;

    //to extend the library for plugins usage
    D.fn = sectionproto = Section.prototype = D.prototype;

    sectionproto.addPage = function (data) {
        this.Pages.push(data)
        conole.log(this.Pages)
    };
    return D;
};

main purpose for this is to use same library for server side and client side operations, so we can have same code base. 主要目的是为服务器端和客户端操作使用相同的库,因此我们可以拥有相同的代码库。

this issue is that when i use this in node app 这个问题是当我在节点应用程序中使用它时

var Diary = require('./diary.js');
var myDiary = new Diary();

console.log(myDiary.addPage('some text on page'))

and run it, it throws an error TypeError: myDiary.addPage is not a function 并运行它,将引发错误TypeError:myDiary.addPage不是一个函数

i am not not sure what to do here to make this work for node js, as our client app is very huge and making changes to it would require some effort if we have to go in some other pattern. 我不确定要在Node js上执行此操作的方法,因为我们的客户端应用程序非常庞大,因此如果必须采用其他模式,则需要进行一些更改才能对其进行更改。

First Question is: 1. is this approach right or we need to look in to something else 2. if this can work on node js app then how with minimum changes to library 第一个问题是:1.这种方法是否正确,还是我们需要研究其他问题?2.如果该方法可以在node js应用程序上运行,那么如何以最少的库更改

The main problem is that you're exporting your overall Diary function, but then using it as though you'd received its return value (the D function) instead. 主要问题是您要导出整个Diary函数,但随后使用它就像收到了它的返回值( D函数)一样。

The way you're exporting it, you'd use it like this: 导出的方式如下:

var Diary = require('./diary.js')();
// Note -------------------------^^
var myDiary = new Diary();

But beware that that means every import will create its own D function and associated things. 但是请注意,这意味着每次导入都会创建自己的D函数和关联的事物。

Alternately, export the result of calling Diary , but then the Diary function has no purpose. 或者,导出调用Diary的结果,但是Diary函数没有任何作用。


Other issues are: 其他问题是:

  • You're falling prey to The Horror of Implicit Globals * by not declaring someFunction or sectionproto . 通过不声明someFunctionsectionproto您就容易成为“隐式全局恐怖 *”的sectionproto Be sure to declare your variables. 确保声明您的变量。
  • The structure is over-complicated without any obvious reason it needs to be so complicated. 该结构过于复杂,没有任何明显的原因,因此需要如此复杂。

* (disclosure: that's a post on my anemic little blog) * (披露:这是我贫乏的小博客上的帖子)

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

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