如何在节点

时间:2016-08-02 23:06:53

标签: javascript node.js web-applications server ecmascript-6

我有一个我创建的代码生成器,我希望能够在服务器上运行它。生成器使用纯本机ECMA6 javascript来呈现HTML标记。

'use strict'
class JSML {

        constructor(stdIn) {
            this.output = '';
            this.parse(stdIn);
            return this.output;
        }

        generateAttributeKeyValueString(key, value) {
            return `${key}='${value}'`;
        }

        camelCaseToDashes(str) {
            return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
        }

        generateDom(vNode) {
            var self = this,
                selfClosingTagNames = ['area','base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr'],
                elmStart = `<${vNode.elm}`,
                elmAttrs = '',
                elmEnd,
                elmContent,
                inSelfClosingTagBool = false;

            selfClosingTagNames.forEach(function(selfClosingTagName) {
                if (vNode.elm === selfClosingTagName) {
                    inSelfClosingTagBool = true;
                }
                else elmEnd = `</${vNode.elm}>`;

            });

            function parseInput(vNode, key) {
                if (!vNode.hasOwnProperty(key)) return;
                var value = vNode[key],
                    // custom types conditons depending on the key and value of the nodes contents
                    isActualInnerValueChildContents = (key === 'inner' && typeof value === 'string'),
                    isChildrenContentArr = (key === 'inner' && Array.isArray(value)),
                    isSingleChildContent = (key === 'inner' && !isChildrenContentArr && (typeof value === 'object')),
                    isAttributeKeyValuePair = (key !== 'elm' && key !== 'inner');
                if (isActualInnerValueChildContents) elmContent = value;
                else if (isAttributeKeyValuePair) elmAttrs += self.generateAttributeKeyValueString(self.camelCaseToDashes(key), value); // Otherwise its an attribute and value pair and should be added to the node string
                else if (isChildrenContentArr) {
                    //Array of multiple child nodes
                    elmContent = '';
                    value.forEach(function(subValue) {
                        elmContent += JSML.run(subValue).output;
                    });
                } 
                else if (isSingleChildContent) elmContent = JSML.run(value).output;
            }

            for (var key in vNode) parseInput(vNode, key);

            if (inSelfClosingTagBool) {
                elmStart += ` ${elmAttrs}/>`;
                inSelfClosingTagBool = false;
                elmEnd = '';
            }
            else elmStart += ` ${elmAttrs}>`; // Close off the html elements start tag now that all possible attributes have been written
            if (elmContent) this.output = elmStart + elmContent + elmEnd 
            else this.output = elmStart + elmEnd
        }

        parse(input) {
            var self = this;
            self.generateDom(input);
        }

    }
    JSML.run = function(appCode, target) {
        var defaultTarget = 'body',
            dom = new JSML(appCode);
            document.querySelectorAll(target || defaultTarget)[0].innerHTML = dom.output;
        return dom;
    }

我希望在NodeJS上利用它,但如果可能的话,没有完全重写(我意识到需要一些fs代码等)。我想将脚本与文件系统包装器一起使用,以及用于将输出直接发送到浏览器以进行呈现的接口。

我使用了Node with Express和其他一些框架,但总是涉及中间件。我希望做什么?

如果是这样的话?

我能够使用npm简单HTTP服务器进行进一步研究后运行它的简单版本,通过读取此线程读取静态HTML我的脚本输出:使用node.js作为简单的Web服务器,与此一起使用thread在Node.js中编写文件,用于将我的脚本输出写入HTML文件。但是主库不会运行。

这是我尝试过的代码:

var fs = require('fs');



var _typeof = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? function (obj) {
    return typeof obj;
} : function (obj) {
    return obj && typeof Symbol === 'function' && obj.constructor === Symbol ? 'symbol' : typeof obj;
};
function _classCallCheck(instance, Constructor) {
    if (!(instance instanceof Constructor)) {
        throw new TypeError('Cannot call a class as a function');
    }
}
var JSML = function () {
'use strict';

  function JSML(stdIn) {
        _classCallCheck(this, JSML);
        this.output = '';
        this.parse(stdIn);
        return this.output;
    }
    JSML.prototype.generateAttributeKeyValueString = function generateAttributeKeyValueString(key, value) {
        return key + '=\'' + value + '\'';
    };
    JSML.prototype.camelCaseToDashes = function camelCaseToDashes(str) {
        return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
    };
    JSML.prototype.generateDom = function generateDom(vNode) {
        var self = this, selfClosingTagNames = [
                'area',
                'base',
                'br',
                'col',
                'command',
                'embed',
                'hr',
                'img',
                'input',
                'keygen',
                'link',
                'meta',
                'param',
                'source',
                'track',
                'wbr'
            ], elmStart = '<' + vNode.elm, elmAttrs = '', elmEnd, elmContent;
        selfClosingTagNames.forEach(function (selfClosingTagName) {
            if (vNode.elm === selfClosingTagName)
                elmEnd = '';
            else
                elmEnd = '</' + vNode.elm + '>';
        });
        function parseInput(vNode, key) {
            if (!vNode.hasOwnProperty(key))
                return;
            var value = vNode[key], isActualInnerValueChildContents = key === 'inner' && typeof value === 'string', isChildrenContentArr = key === 'inner' && Array.isArray(value), isSingleChildContent = key === 'inner' && !isChildrenContentArr && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object', isAttributeKeyValuePair = key !== 'elm' && key !== 'inner';
            if (isActualInnerValueChildContents)
                elmContent = value;
            else if (isAttributeKeyValuePair)
                elmAttrs += self.generateAttributeKeyValueString(self.camelCaseToDashes(key), value);
            else if (isChildrenContentArr) {
                elmContent = '';
                value.forEach(function (subValue) {
                    elmContent += JSML.run(subValue).output;
                });
            } else if (isSingleChildContent)
                elmContent = JSML.run(value).output;
        }
      for (var key in vNode){
        if (vNode.hasOwnProperty(key)) parseInput(vNode, key);
      }

        elmStart += ' ' + elmAttrs + '>';
        if (elmContent)
            this.output = elmStart + elmContent + elmEnd;
        else
            this.output = elmStart + elmEnd;
    };
    JSML.prototype.parse = function parse(input) {
        var self = this;
        self.generateDom(input);
    };
    return JSML;
}();
JSML.run = function (appCode, target) {
    var defaultTarget = 'body', dom = new JSML(appCode);
    document.getElementsByTagName(target || defaultTarget)[0].innerHTML = dom.output;
    return dom;
};

fs.writeFile("index2.html", JSML.run({
   elm: 'img',
   src: 'http://placehold.it/50x50'
}, function(err) {
    if(err) {
        return console.log(err);
    }

    console.log("The file was saved!");
});

我一直得到&#34;意外的令牌;&#34;在generateView.js中,如98

主要思想是我需要在我的服务器上运行JavaScript,生成提供从我的脚本生成的内容所需的标记,以便只说端口80.

谢谢,我愿意接受任何有用的建议。

1 个答案:

答案 0 :(得分:0)

如果我理解,只需将您的代码放入js文件,例如script.js。并运行node script.js

也许你必须将你的课程包装到模块中,这是开始学习的好点https://nodejs.org/api/modules.html

或者如果您想要服务器,请尝试Express js

const express = require('express');
const app = express();

const JSML = express('./JSML'); // <--- your module
let jsml = newJSML();

app.get('/home', function(req, res){
  res.send(jsml.run());
});

app.listen(80);