1

I've been trying to read a txt file from a URL and output my own text file using nodejs

Can anyone tell me what am I doing wrong in my code?

var fs = require('fs');
var request = require('request');
var stream = fs.createWriteStream("my_file.txt");



request('http://redsismica.uprm.edu/Data/prsn/EarlyWarning/Catalogue.txt', function (error, response, body) {
  if (!error && response.statusCode == 200) {

    firstLine = body.substring(0, body.indexOf('\n'));
    console.log(firstLine);

    stream.once('open', function(fd) {
    wstream.write(firstLine, 'utf16le');//stream.write(firstLine);
    stream.end();
});
  }
})

1 Answer 1

2

Not sure what wstream is in your code but with request you can pipe your response directly to your write stream.

var stream = fs.createWriteStream('my_file.txt', { defaultEncoding: 'utf16le' });

stream.once('error', function(err) {
  console.log(err);
});

stream.once('end', function() {
  console.log('response written');
});

request('http://redsismica.uprm.edu/Data/prsn/EarlyWarning/Catalogue.txt')
  .once('error', function(err) {
    console.log('Request Error: ' + err);
  })
  .pipe(stream);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.