• Send data in a file with FS
  • Content-type: view the Content Type: tool.oschina.net/commons
  • Different resources have different content-Types
  • Images do not need to be coded
  • Encoding is typically specified only for character data
var http = require('http')
var fs = require('fs')

var server = http.createServer()

server.on('request'.function (req, res) {
  // / index.html
  var url = req.url

  if (url === '/') {
    // Definitely not
    // res.end('
       < HTML lang = "en" > < head > < meta charset = "utf-8" > < title > Document < / title > < / head > < body > < h1 > home page < / h1 > < / body > / HTML > ')

    // What is sent is still in the file
    fs.readFile('./resource/index.html'.function (err, data) {
      if (err) {
        res.setHeader('Content-Type'.'text/plain; charset=utf-8')
        res.end('File read failed, please try again later! ')}else {
        // Data is binary by default and can be converted to a string we can recognize through.tostring
        Res.end () supports two data types, binary and string
        res.setHeader('Content-Type'.'text/html; charset=utf-8')
        res.end(data)
      }
    })
  } else if (url === '/baby') {
    // url: uniform resource locator
    // A URL eventually corresponds to a resource
    fs.readFile('./resource/ab2.jpg'.function (err, data) {
      if (err) {
        res.setHeader('Content-Type'.'text/plain; charset=utf-8')
        res.end('File read failed, please try again later! ')}else {
        // Data is binary by default and can be converted to a string we can recognize through.tostring
        Res.end () supports two data types, binary and string
        // There is no need to specify the encoding for the image, because we usually refer to the encoding: character encoding
        res.setHeader('Content-Type'.'image/jpeg')
        res.end(data)
      }
    })
  }
})

server.listen(3000.function () {
  console.log('Server is running... ')})Copy the code
  • The default access is http://localhost:3000/

  • Access to images path: http://localhost:3000/img