0

I'm using node.js to build a webapp and I need to use synchronous request for getting a file.

I know how to get the file locally:

var fs = require('fs');
var myFile = fs.readFileSync('myFile.html', 'utf8');

but I want to read this file from the web like this:

var fs = require('fs');
var myFile = fs.readFileFromWebSync('http://www.theweb.com/myFile.html', 'utf8');

How do I read a file synchroniously from web?

I need it to be synchronious because this is part of a single build process and not part of a web server.

1
  • Using asynchronous calls is not relevant only when building web servers. You really should use them also in your case, because it will save your CPUs. Commented Feb 13, 2014 at 12:39

2 Answers 2

3

You cannot use the filesystem tools to read from an URL. You should use this library

As one can see in the example you should do the following:

request('http://www.theweb.com/myFile.html').pipe(fs.createWriteStream('myFile.html'))

This would read from the provided URL into the pointed file on your filesystem. You will find on the page of the library multiple examples.

Sign up to request clarification or add additional context in comments.

4 Comments

Though it seems like a nice solution. The file that it creates is empty.
@Alon currently I don't have a system running node at hand to try it also. I would recommend publishing the content retrieved using the log. I would try it again later. Thank you
@Alon - just tried the same line I posted for you in the node console-> it works like a charm, please let me know if I can help you with something
sorry for the late response. it worked like a charm. thank you so much!
1

Technically, you can use require('child_process').execSync('curl http://www.theweb.com/myFile.html') in current master (v0.11.11).

But you'd better have really good reason for doing that.

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.