Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6969727
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T16:37:05+00:00 2026-05-27T16:37:05+00:00

I’m a long time PHP (CodeIgniter & WordPress) developer that only recently wanted to

  • 0

I’m a long time PHP (CodeIgniter & WordPress) developer that only recently wanted to learn a few other languages. I’ve set out to learn Ruby (on Rails, and Sinatra), Python (w/ Flask framework) and Javascript with node.js.

I decided to create the most basic application I can think of, a URL expander, using each of these languages. I have managed to create a working version in every language, except node.js and Javascript.

I kinda know my problem, I know it is related to callbacks. I know I’m not doing it right. I get the basic idea of callbacks, but I just cannot figure out how to fix this mess I have created.

This is my whole code:

var http = require('http');
var url = require('url');
function expand() {
    var short = url.parse('http://t.co/wbDrgquZ');
    var options = {
        host: short.hostname,
        port: 80,
        path: short.pathname
    };
    function longURL(response) {
        console.log(response.headers.location);
    }
    http.get(options, longURL);
}

function start() {
    function onRequest(request, response) {
        console.log("Request received.");
        response.writeHead(200, {
            "Content-Type": "text/plain"
        });
        response.write("Hello World");
        expand();
        response.end();
    }
    http.createServer(onRequest).listen(8888);
    console.log("Server has started.");
}
start();

The server starts, and when a request is made, it calls the expand function which returns the expanded URL in the terminal. I’m trying to get it to print in the browser.

Any help is appreciated. Thanks in advance.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T16:37:05+00:00Added an answer on May 27, 2026 at 4:37 pm

    You’ve made a few flaws.

    You should rewrite expand to pass the url in and pass a callback in. Any function that does anything asynchronous generally has the signature (data, callback) in node. This basically allows you to say I want this function to do something then tell me when it’s done.

    function expand(urlToParse, callback) {
        // note we pass in the url this time
        var short = url.parse(urlToParse);
        var options = {
            host: short.hostname,
            port: 80,
            path: short.pathname
        };
        // note we store the clientRequest object temporarily
        var clientRequest = http.get(options, extractRealURL);
    
        // Always attach the error handler and forward any errors
        clientRequest.on("error", forwardError);
    
        function extractRealURL(res) {
            callback(null, res.headers.location);    
        }
    
        function forwardError(error) {
            callback(err);    
        }
    }
    

    Here the callback is expected to have the signature of (err, data) which almost all callbacks in node have. We’ve also added error handling which is a must.

    We now change onRequest to actually call expand properly

    function onRequest(request, response) {
        // parse the incoming url. true flag unpacks the query string
        var parsedUrl = url.parse(request.url, true),
            // extract the querystring url. 
            // http://localhost:8888/?url=http://t.co/wbDrgquZ
            urlToExpand = parsedUrl.query.url;
    
        // call expand with the url and a callback
        expand(urlToExpand, writeResponse);
    
        function writeResponse(error, newUrl) {
            // handle the error case properly
            if (error) {
                response.writeHead(500, { 'Content-Type': 'text/plain'});
                // early return to avoid an else block
                return response.end(error.message);
            }
            response.writeHead(200, { 'Content-Type': 'text/plain'});
            // write the new url to the response
            response.end(newUrl);
        }
    }
    

    Here we have added error handling logic and also unpacked the actual url to expand from the query string.

    Generally the pattern of doSomething<data, callback<err, result>> works very well in node.js.

    It’s the exact same as let result = doSomething<data> mayThrow err that you expect in your normal blocking languages except it’s asynchronous.

    Note that the alternative option of passing the ServerResponse object into the function is frowned upon, by doing so your creating unnecessary hard coupling between the expand function and the server response.

    The expand function should only expand an url and return the expanded url, it has no business doing IO itself.

    Full code

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I'm trying to create an if statement in PHP that prevents a single post
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I want to count how many characters a certain string has in PHP, but
I would like to count the length of a string with PHP. The string
this is what i have right now Drawing an RSS feed into the php,
I've got a string that has curly quotes in it. I'd like to replace
I have a French site that I want to parse, but am running into

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.