Ask coding questions

← Back to all posts
How to return fetch contents from a node.js module?
DREWNOLT (28)

I am trying to make a module to simplify the node-fetch module in node.js. This is what I have so far:

const fetch = require('node-fetch')

module.exports = function(url) {
  try{
  fetch(url)
  .then(res => res.text())
  .then(text => {
    return text;
  });}
  catch(err){
    return 'Error';
  }
}

This does not seem to work, as nothing is returned except for undefined. How do I make this work?

Comments
hotnewtop
TAL0S (5)

node-fetch takes time to run, because it takes time to communicate over the web, but js won't wait for it, so you need to use a Promise. You are currently just returning to the "fetch()" function, not your actual function.

Here is the correct code to make it work:

const fetch = require("node-fetch");

module.exports = function(url) {
    return new Promise((resolve, reject) => {
        try {
            fetch(url).then(res => res.text()).then(text => {
                return resolve(fetch);
            });
        } catch(err) {
            resolve(err);
        }
    }
}

And to use it, you would use this code, assuming that myFunc(url) is your function name

const myFunc = require("./file");

myFunc("https://google.com").then(content => {
    console.log(content);
});

If this still doesn't help, try looking here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises