How do I return value from file reading and how to remove the first argument on res.write()

Hi guys,

I found these code snippets on the internet and tried to edit it to my specific need but I can’t go any further. Can you please help me solve it.

The first file:

var http = require(‘http’);
var dt = require(’./readfiles’);

http.createServer(function (req, res) {
res.writeHead(200, {‘Content-Type’: ‘text/html’});
res.write(": " + dt.readfiles());
res.end();
}).listen(8080);

The second file:

exports.readfiles = function() {
var fs = require(‘fs’);
var file = ‘text1.txt’;

fs.readFile('./' + file, 'utf-8', function(err, data){
	if (err) { console.log(err); }
	return data;
});

};

Thank you,

Hi @ketting00, you’re not returning anything from dt.readfiles(); and since that function performs an asynchronous operation, returning an immediate return value wouldn’t work anyway. So you’ll either have to return a promise, or have dt.readfiles() also take a callback – the simplest way would be to just forward a callback to fs.readFile:

// readfiles.js
var fs = require('fs')

exports.readfiles = function (callback) {
  var file = 'text1.txt'

  fs.readFile('./' + file, 'utf-8', callback)
}

// index.js
var http = require('http')
var dt = require('./readfiles')

http.createServer(function (req, res) {
  dt.readfiles(function (err, data) {
    if (err) {
      res.writeHead(500)
      return res.end(err)
    }
    
    res.writeHead(200, { 'Content-Type': 'text/html' })
    res.end(data)
  })
}).listen(8080)
1 Like