Our next step will be using the streams to work with network connections. And we will start from delivering files to a visitor. As you may remember, we’ve already had a task like this: if a visitor requires the following url, you will give him the file. Let us create a file pipe.js with the following code (for your convenience, you can download code' lesson from the repository because we'll need an HTML file from there):
This article will deal with how to create a web server in Node.js, which will return a file to a user from a public directory. You may wonder: why do we need Node.js here? Why can’t we use another server? You question surely does make sense. Yes, for returning files other servers are generally more effective. From the other side, Node.js works pretty well, too. Second, before returning a file it can also perform some intellectual activities: for example, refer to a database, check out whether a user is permitted to access the file and give the file to him, if it’s permitted.
Hey, guys! If your habit is to learn something deeply and thoroughly, this article is for you. Here we will try to answer the questions that you will have sooner or later in the process of development. These answers require deep understanding of how Node.js works. For example, here (serverAsync.js see the files of our previous lesson) an asynchronous call is used for reading a file: