Serving Files
Last updated: 4 - 5 - 2019

Serving static content in ZinkyJS respects the principle of modularity that comes with the framework.

Global Files

By default, ZinkyJS serves all the files in 'public' folder through a special built-in module called file.
Those settings are editable by staticFolder for the folder name and staticModuleName for the special module name.

To test that, create 'public/main.js' with this line:

 alert("I'm a global js file");

And import the file in 'app_modules/home/views/index.pug':

 block content
  h3 This is my page content 
  p I love ZinkyJS
  script(src="/file/main.js")

Visit localhost:3000

Module's Files

You can put static content specific to module into its client folder and get them by a special action called file.
These settings are not editable.

To test that, put any image in 'app_modules/home/client' and import the file in 'app_modules/home/views/index.pug':

 block content
  img(src="/home/file/imageName.ext")
  h3 This is my page content 
  p I love ZinkyJS
  script(src="/file/main.js")

Note: Even if 'home' module is aliased by '', you still have to write '/home/file' if you want to get its static content.

If Not Found

If the file does not exist, ZinkyJS will throw:
 { statusCode: 404 }

Check the error handling course for further details.

Programmatically

If in any case we want to send a file from an operation, we can use some of the res methods that were developed for this purpose:

- sendFile("filePath")
: Responds with the file at the given path.
To test it, add the following method to "app_modules/home/index.js" then visit localhost:3000/myimage:
 GET_myimage(req, res, next) {
  res.sendFile(__dirname + "/client/imageName.ext") // the image you added earlier
}

- download("filePath", "fileName")
: Responds with the file at the given path as an “attachment”. Typically, browsers will prompt the user for download. Override the default filename with the "fileName" parameter.
To test it, add the following method to "app_modules/home/index.js" then visit localhost:3000/myimage:
 GET_myimage(req, res, next) {
  res.download(__dirname + "/client/imageName.ext", "my_image.ext") // the image you added earlier
}

- sendAsFile("content", "extension")
: Responds with the content as a file that has the given extension.
Imagine you have an svg that you wrote in Pug and after you render it, you want to send it as file not as html. You'll just have to write this:
 GET_svg(req, res, next) {
  // We'll say, you have a file name 'svg.pug' in 'views'
  var content = this.v("svg").render()
  res.sendAsFile(content, "svg");
}

Next Course: Inheritance