使用document.cookie将客户端javascript转换为节点模块

时间:2015-03-21 07:12:25

标签: javascript node.js cookies commonjs

如何在节点中使用document.cookie?请在回复之前进一步阅读。

我对节点模块的尝试:

var myModule = module.exports = function myModule(options) {
}

moduleName.getCookie = function(cname) {
    'use strict';
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }
    return "";
};

moduleName.setCookie = function(cname, cvalue, exdays) {

    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
};

index.js

我尝试在index.js中使用jsdom模块

var jsdom = require('jsdom');
var window = jsdom.jsdom().parentWindow;
var Cookies = require('cookies-js')(window);

mymodule.js

myModule.prototype.getCookie = function(cname) {
    Cookies.get(cname);
};

myModule.prototype.setCookie = function(cname, cvalue) {
    Cookies.set(cname, cvalue);
};

但我不确定如何将Cookies中引用的index.js传递给foo.js中的myModule

1 个答案:

答案 0 :(得分:0)

我不太确定我完全理解这个问题,但为什么你不能放

var Cookies = require('cookies-js')(window);
myModule.prototype.getCookie = function(cname) {
    Cookies.get(cname);
};

myModule.prototype.setCookie = function(cname, cvalue) {
    Cookies.set(cname, cvalue);
};

进入foo.js?