Search code examples
node.jshttpsplitfsstringify

Node.js - selecting random file and reading its content then spliting it


So, i want to select random file, read it's content, split it and stringify it.
But problem is the file always is the same. (i refreshed the page like 10 times)
Code:

//require
var fs = require('fs');
var http = require('http')
//require
var files = fs.readdirSync('./pathtofiles');

function randomfile(list){
    return list[Math.floor(Math.random() * files.length)];
}

var location = './zdj' + '/' + (randomfile(files))

var data = fs.readFileSync(location, "utf8");
var splittext = data.split("||")

var app = http.createServer(function(req,res){
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify({"test1": splittext[0], "test2": splittext[1], "test3": splittext[2]}));
});
app.listen(3000);

File(s) content example: The||example||file


Solution

  • The "random" file is determined before the server is started. In order to do this for every request you need to call randomfile(...) in the request-callback:

    const app = http.createServer( (req,res) => {
        const location = './zdj' + '/' + (randomfile(files))
        const data = fs.readFileSync(location, "utf8");
        const splittext = data.split("||")
        res.setHeader('Content-Type', 'application/json');
        res.end(JSON.stringify({"test1": splittext[0], "test2": splittext[1], "test3": splittext[2]}));
    });
    

    Note:

    1.) you should use let/const instead of var nowadays (see this for more info)

    2.) readFileSync blocks, you should consider using a non-blocking read-operation, e.g. fs.promises.readFile()