How can I use the browser module to adapt the xml2js node module for the browser?

I am learning nodejs with Noodcook 2nd edition book.

In Chapter 3, Sending Serialized Data from Client to Server,

I ran into an obstacle.

below is the add_profile_server.js file

var http = require('http');
var fs = require('fs');
var path = require('path');
var profiles = require('./profiles');
var xml2js = require('xml2js');

var index = fs.readFileSync('add_profile_index.html');
var clientXml2js = fs.readFileSync('./xml2js.js');

var routes, mimes = {
    js: "application/javascript",
    json: "application/json",
    xml: "application/xml"
};

function output(content, format, rootNode) {
    if (!format || format === 'json') {
        return JSON.stringify(content);
    }
    if (format === 'xml') {
        return (new xml2js.Builder({rootName: rootNode})).buildObject(content);
    }
}



routes = routes = {
    'profiles': function (format) {
        return output(Object.keys(profiles), format);
    },
    '/profile': function (format, basename) {
        return output(profiles[basename], format, basename);
    },
    'xml2js' : function(ext) {
        if (ext === 'js') { return clientXml2js; }
    }
};

function updateProfiles(profile, type, cb) {
    var name = Object.keys(profile).pop();
    profiles[name] = profile[name];
    cb(output(profiles[name], type, name));
}

function addProfile(request, cb) {
    var pD = ''; //post data
    request
    .on('data', function (chunk) { pD += chunk; })
    .on('end',function() {
        var contentType = request.headers['content-type'];
        if (contentType === 'application/json') {
            updateProfiles(JSON.parse(pD), 'json', cb);
        }
        if (contentType === 'application/xml') {
            xml2js.parseString(pD, {
                explicitRoot: false,
                explicitArray: false
            }, function(err, obj) {
                updateProfiles(obj, 'xml', cb);
            });
        }
    });
}


http.createServer(function (request, response) {
var dirname = path.dirname(request.url),
    extname = path.extname(request.url),
// Return the last portion of a path. (optional-extname: return only file name on mattached ext)
    basename = path.basename(request.url, extname);

console.log("URL: "+request.url);
console.log("dirname:"+dirname);
console.log("extname:"+extname);
console.log("basename:"+basename);
console.log("");


    extname = extname.replace('.', ''); //remove period

    if (request.method === 'POST') {
        addProfile(request, function(output) {
            response.end(output);
        });
    return;
    }
    response.setHeader("Content-Type", mimes[extname] ||'text/html');
// If the subroute exists in the routes object, we call the method stored at that namespace passing in basenameand extname
    if (routes.hasOwnProperty(dirname)) {
        response.end(routes[dirname](extname, basename));
        return;
    }
    if (routes.hasOwnProperty(basename)) {
        response.end(routes[basename](extname));
        return;
    }
    response.end(index);    
}).listen(8080);

      

and below is the add_profile_index.html file

<!DOCTYPE html>
<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

        <style>
            #frm, #raw {display:block; float:left; width:210px}
            #raw {height:150px; width:310px; margin-left:0.5em}
            #add {display:block; float:left; margin-left:1.5em}
            #add div {display:table-row}
            #add label {float:left; width:5.5em}
                 div button {float:right}
        </style>
        <title> INDEX </title>
    </head>

    <body>
        <form id="frm">
            Profile: <select id="profiles">
            <option> </option>
            </select>
            <br></br>

            Format:<select id="formats">
            <option value="json"> JSON </option>
            <option value="xml"> XML </option>
            </select>
            <br></br>
            <div id="output"></div>
        </form>
        <textarea id="raw"></textarea>

        <form id="add">
            <div><label>profile name</label><input name="profileName"> </input></div>
            <div><label>name</label><input name="name"></input></div>
            <div><label>irc</label><input name="irc"></input></div>
            <div><label>twitter</label><input name="twitter"></input></div>
            <div><label>github</label><input name="github"></input></div>
            <div><label>location</label><input name="location"></input></div>
            <div><label>description</label><input name="description"></input></div>
            <div><button>Add</button></div>
        </form>

        <script src="xml2js.js"></script>
    </body>

    <script>
        function load(done) {
            $.get('http://localhost:8080/profiles',

                function (profile_names) {
                    $.each(profile_names, function (i, pname) {
                        $('#profiles').append('<option>' + pname + '</option>');
                    });
                done && done();
                },
            'json');
        }
        load(); 
        $('#add').submit(function(e) {
            var output, obj = {}, format = $('#formats').val(), profileName;
            e.preventDefault();
            $.each($(this).serializeArray(), function(i, nameValPair) {
                obj[nameValPair.name] = nameValPair.value; //form an object
            });
            profileName = obj.profileName; 
            delete obj.profileName;

            obj = {_: obj}; 
            obj[profileName] = obj._;   
            delete obj._;

            output = (format === 'json') ? JSON.stringify(obj) :
             (new xml2js.Builder({rootName: profileName})).buildObject(obj);
            $.ajax({ 
                    type: 'POST', 
                    url: '/', data: output,
                    contentType: 'application/' + format, dataType: 'text',
                    success: function(response) {
                        $('#raw').val(response);
                        $('#profiles').html('<option></option>');
                        load(function () {
                            $('#profiles').val(profileName);
                        });
                    }
            });
        });
    </script>

</html>

      

Before starting the server, we need to enter the command below

npm -g install browser

browse node_modules / xml2js -s xml2js -o xml2js.js

I think I am just following the book to generate the example code, but

the above code doesn't work, especially when working with XML format. I think the problem is with the browser.

I have looked at https://www.npmjs.org/package/browserify to understand the browser, but I find it very difficult to understand and use the module correctly.

Can you tell me what the problem is?

Thank!

+3


source to share


2 answers


I found the answer myself.

The main problem was browsing node_modules / xml2js -s xml2js -o xml2js.js

He did not work.

So, we need to adapt the new browser module.

First make any javascript file (xml2jsM.js) containing below code. 'use strict';

var _ = require('xml2js');

var logUnderscoreVersion = function() {
  console.log(_.VERSION);
}

module.exports = logUnderscoreVersion;

      



and then install the underline module. (npm set underscore)

and then create a package file. (rename xml2jsM.js> bundle.js)

and then include in add_profile_index.html

(You can link these steps at http://lincolnloop.com/blog/untangle-your-javascript-browserify/ )

If you have any questions, please let me know.

Thank you ~

+4


source


I managed to find some examples here http://opennodes.arecord.us/md/xml2js.md to see if the examples are helpful to you.

Try something like this?

Instead



(new xml2js.Builder({rootName: profileName})).buildObject(obj);

      

Try:

var xml2js = require('xml2js');
var builder = new xml2js.Builder({rootName: profileName}));
builder.buildObject(obj);

      

-2


source







All Articles