1

I'm just really new on Node and Express. Trying to pass a function instead of text on my route but it seems not working. I just looked up at documentation there, They mentioned only text with req.send() method. I'm trying to pass here function's but it's not working. and also the alert() not working like this req.send(alert('Hello world')) it say's alert isn't defined or something similar.

**Update: ** I'm trying to execute this library with express and node https://github.com/przemyslawpluta/node-youtube-dl

I'm trying to do here pass functions like this

function blaBla() {
    var youtubedl = require('youtube-dl');
    var url = 'http://www.youtube.com/watch?v=WKsjaOqDXgg';
    // Optional arguments passed to youtube-dl.
    var options = ['--username=user', '--password=hunter2'];
    youtubedl.getInfo(url, options, function(err, info) {
      if (err) throw err;

      console.log('id:', info.id);
      console.log('title:', info.title);
      console.log('url:', info.url);
      console.log('thumbnail:', info.thumbnail);
      console.log('description:', info.description);
      console.log('filename:', info._filename);
      console.log('format id:', info.format_id);
});
}

app.get('/', (req, res) => {  
  res.send(blaBla());
})

**Instead of **

app.get('/', function (req, res) {
  res.send('Hello World!')
})

I hope you guy's understood my question.

Code Cooker
  • 881
  • 14
  • 19
  • Have you tried passing the function as a string and having the browser call eval() on the received string? – Mark S. Jun 10 '17 at 18:28
  • Wait as a string? What does that means I don't understand things are really good on that. So please if you just give me an example that would be great. – Code Cooker Jun 10 '17 at 18:30
  • Alert will not be defined on your server, it is part of the web-api. Also you might be a bit confused about how function execution works at run time. In your send examples you're sending the return value of function blaBlah, not the function itself. – Shadowfool Jun 10 '17 at 18:31
  • Try `req.send('alert('Hello world')')` And then on the receiving end of the browser you call `eval(javascriptString)` with the string that is received – Mark S. Jun 10 '17 at 18:32
  • No, it's throwing a box of error now.. :( – Code Cooker Jun 10 '17 at 18:35
  • This will all work fine if `blaBla()` is a regular function that synchronously returns a string. So, if it isn't working, then there's something wrong inside of `blaBla()` and you need to show us that code. – jfriend00 Jun 10 '17 at 18:51
  • In your `alert()` example, that is not a function that is defined in node.js. If you're trying to get the browser to execute an `alert()` and the browser is expecting a web page, then you need to send HTML that contains a ` – jfriend00 Jun 10 '17 at 18:53
  • Also, you never do `req.send()`. It's always `res.send()` or whatever the second argument is named. – jfriend00 Jun 10 '17 at 19:09

2 Answers2

1

res.send() expects a string argument. So, you have to pass a string.

If you want the browser to execute some Javascript, then what you send depends upon what kind of request is coming in from the browser.

If it's a browser page load request, then the browser expects an HTML response and you need to send an HTML page string back. If you want to execute Javascript as part of that HTML page, then you can embed a <script> tag inside the page and then include Javascript text inside that <script> tag and the browser will execute that Javascript when the page is parsed and scripts are run.

If the route is in response to a script tag request, then you can return Javascript text as a string and you need to make sure the MIME type appropriately indicates that it is a script.

If the route is in response to an Ajax call, then it all depends upon what the caller of the Ajax call expects. If they expect a script and are going to execute the text as Javascript, then you can also just send Javascript text as a string. If they expect HTML and are going to process it as HTML, then you probably need to embed the <script> tag inside that HTML in order to get the Javascript executed.

In your example of:

response.send(blaBla());

That will work just fine if blaBla() synchronously returns a string that is formatted properly per the above comments about what the caller is expecting. If you want further help with that, then you need to show or describe for us how the request is initiated in the browser and show us the code for the blaBla() function because the issue is probably in the blaBla() function.

There are lots of issues with things you have in your question:

  1. You show req.send(alert('Hello world')) in the text of your question. The .send() method belongs to the res object, not the req object (the second argument, not the first). So, that would be res.send(), not req.send().

  2. In that same piece of code, there is no alert() function in node.js, but you are trying to execute it immediately and send the result with .send(). That won't work for a bunch of reasons.

  3. Your first code block using blaBla() will work just fine as long as blaBla() returns a string of the right format that matches what the caller expects. If that doesn't work, then there's a problem with what blaBla() is doing so we need to see that code.

  4. Your second code block works because you are send a string which is something the caller is equipped to handle.


Update now that you've shown the code for blaBla().

Your code for blaBla() does not return anything and it's asynchronous so it can't return the result. Thus, you cannot use the structure response.send(blaBla());. There is no way to make that work.

Instead, you will need to do something different like:

blaBla(response);

And, then modify blaBla() to call response.send(someTextValue) when the response string is known.

function blaBla(res) {
    var youtubedl = require('youtube-dl');
    var url = 'http://www.youtube.com/watch?v=WKsjaOqDXgg';
    // Optional arguments passed to youtube-dl.
    var options = ['--username=user', '--password=hunter2'];
    youtubedl.getInfo(url, options, function(err, info) {
        if (err) {
            res.status(500).send("Internal Error");
        } else {
            console.log('id:', info.id);
            console.log('title:', info.title);
            console.log('url:', info.url);
            console.log('thumbnail:', info.thumbnail);
            console.log('description:', info.description);
            console.log('filename:', info._filename);
            console.log('format id:', info.format_id);
            // construct your response here as a string
            res.json(info);
        }
    });
}

Note also that the error handling does not use throw because that is really not useful inside an async callback.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • I'm Updating my answer will you have a look on that please? @jfriend00 – Code Cooker Jun 11 '17 at 04:34
  • Is this make sense? Then how do I get a response back from that function? how do I console or output the information, and what are we sending with `someStringResponse` ? – Code Cooker Jun 11 '17 at 06:14
  • How can I just output information from the function that I'm sending with blaBal() – Code Cooker Jun 11 '17 at 06:15
  • If you just can give me a working example, That would be really great :) – Code Cooker Jun 11 '17 at 06:17
  • @Smalldeveloper - I've given you a working example. All you have to do is construct the string you want to send as the response and substitute that in place of `someStringResponse`. Since you haven't told us what you want the response to actually be, I don't know what else to show you. – jfriend00 Jun 11 '17 at 14:34
  • @Smalldeveloper - A function that obtains it's result asynchronously like `blaBla()` cannot directly return that result. You have to either use the value inside the async callback (like I show) or you have to return the value via a callback or a promise and have the caller use the value that way. See [How do I return the response from an asynchronous call](https://stackoverflow.com/a/14220323/816620) for a lot more explanation. – jfriend00 Jun 11 '17 at 14:37
  • The response back I want back is `console.log` messages. How to get responses like that? If this is a normal function and request has created successfully with youtubedl plugin then on the function the response i should get back easily like the console messages. So how can get response back in this express app – Code Cooker Jun 11 '17 at 17:19
  • Ok I think i got it, what you were trying to make me understand. Now one more thing is where routes ? as you given an example sending `res.send(someStringResponse);` from a function. Now where to define the route ? I mean on which routes is that `res.send(someStringResponse);` gonna work? Please give a working example on that too. Thanks for your help. @jfriend00 – Code Cooker Jun 11 '17 at 17:26
  • @Smalldeveloper - If you just want to send back the `info` object, then you can use `res.json(info)` to send that object as JSON. I've modified my answer to show that. I think I've more than answered your original question. This site does not encourage people to continue asking more and more questions in comments. It is a question/answer site, not a long running discussion site. If you have a new question, then you can ask another question. I think your original question has been more than answered now. – jfriend00 Jun 11 '17 at 17:34
  • Sorry to say but this didn't help me. – Code Cooker Jun 11 '17 at 21:59
  • @smalldeveloper - i can no longer guess what you are trying to do. If you explain the result you are trying to achieve in your question in a much more complete fashion, perhaps someone else can help. I answered what i thought ypu were asking. – jfriend00 Jun 11 '17 at 22:14
1

No one just could help me with that and after finding things are alone I got to know how to do this. In express there is something called middleware we have to use that thing to get this kind of matter done. Those who are really expert or have working experience with express they know this thing.

to using functions with express you need to use middleware.

like below I'm showing

const express = require('express')
const youtubedl = require('youtube-dl');
const url = 'https://www.youtube.com/watch?v=quQQDGvEP10';
const app = express()  
const port = 3000

function blaBla(req, res, next) {
    youtubedl.getInfo(url, function(err, info) {
        console.log('id:', info.id);
            console.log('title:', info.title);
            console.log('url:', info.url);
            // console.log('thumbnail:', info.thumbnail);
            // console.log('description:', info.description);
            console.log('filename:', info._filename);
            console.log('format id:', info.format_id);
    });
    next();
}
app.use(blaBla);
app.get('/', (request, response) => {  
  response.send('Hey Bebs, what is going on here?');
})


app.listen(port, (err) => {  
  if (err) {
    return console.log('something bad happened', err)
  }

  console.log(`server is listening on ${port}`)
})

And remember that you must need to use app.use(blaBla); on top of getting your route. Otherwise this might not work.

Code Cooker
  • 881
  • 14
  • 19