verunar
verunar

Reputation: 874

How to change data that comes from a text file in node.js?

I am learning node.js and made a simple app, where I have a text file called 'input.txt' with some data and printing it out in localhost. I would like to add some function, for example remove all *, but I get an error with split function. Can you help where I am going wrong? Is there a way to change text file data somehow?

var http = require('http');
var fs = require('fs');
http.createServer(function(req, res) {
    fs.readFile('input.txt', function(err, data) {
        res.writeHead(200, {
            'Content-Type': 'text/html'
        });
        var data = data.split('*')
        res.write(data);
        res.end();
    });
}).listen(8080);

and here is the example of 'input.txt'

veronika*sandra*carol*bye*

Upvotes: 0

Views: 93

Answers (2)

Arif Khan
Arif Khan

Reputation: 5069

First of all, you should check error and then it is safe to convert into a string like

var http = require('http');
var fs = require('fs');
http.createServer(function(req, res) {
    fs.readFile('input.txt', function(err, data) {
        res.writeHead(200, {
            'Content-Type': 'text/html'
        });
        if(err) {
            console.log('Error: ', err);
            res.end();
        } else {
            data = data && data.toString().replace(/\*/g, '');
            res.write(data);
            res.end();
        }
    });
}).listen(8080);

Upvotes: 0

Use split and join


let dataFile=data.split('*').join(' ');


res.write(dataFile);

Upvotes: 1

Related Questions