Ask coding questions

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

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) {
  .then(res => res.text())
  .then(text => {
    return text;
    return 'Error';

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

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) {

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

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

myFunc("").then(content => {

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