Не удается получить включенный файл js в приложении Node.js - PullRequest
0 голосов
/ 30 декабря 2018

У меня есть простое чистое приложение Node.js.Его структура выглядит следующим образом:

enter image description here

The problem is I cannot get common.js properly.
The app.mjs consists of:
import http from 'http'
import fs from 'fs'
import nStatic from 'node-static'
import chalk from 'chalk'
import debug from 'debug'

const output = debug('app')

const fileServer = new nStatic.Server('./public')

const server = http.createServer((req, res) => {
  fileServer.serve(req, res)
  const Url = new URL(req.url, 'http://localhost:3000/')
  const fileExt = Url.pathname.split('/').pop().split('.').pop()
  let aType = ''

  switch (fileExt) {
    case 'ico':
      aType = 'image/vnd.microsoft.icon'
      break
    case 'js':
      aType = 'application/javascript'
      break
    case 'json':
      aType = 'application/json'
      break
    default:
      aType = 'text/html'
      break
  }
  res.writeHead(200, { 'Content-type': aType })

  const filePath = 'views/node.html'
  // using readFile
  fs.readFile(filePath, (err, content) => {
    if (err) {
      console.log('Error has occured: ', err)
      res.end(content)
    } else {
      res.end(content)
    }
  })
})

server.listen(3000, () => output(`Listen to me ${chalk.green('3000')}`))

После запуска можно найти common.js

enter image description here

но возвращает содержимое views/index.html вместо самого сценария:

enter image description here

common.js:

console.log('Common js here to help!')

Также выводятся ошибки: enter image description here Итак, предположительно, это что-то простое, но я не могу понять, что именно.

1 Ответ

0 голосов
/ 30 декабря 2018

Вы обслуживаете один и тот же файл при каждом запросе.Эти строки всегда будут отвечать содержимым файла "node.html".

const filePath = 'views/node.html'
fs.readFile(filePath, (err, content) => {
      res.end(content)
});

В соответствии со статической нодой документацией правильный способ обслуживания каталога:

const http = require('http');
const NodeStatic = require('node-static');

const fileServer = new NodeStatic.Server('./public');

const server = http.createServer(function (request, response) {
    request.addListener('end', function () {
        fileServer.serve(request, response);
    }).resume();
});
server.listen(8080);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...