Máy chủ tệp NodeJS

Bất kể chúng ta xem trang web nào, sẽ có hình ảnh, chẳng hạn như Medium, Twitter, v.v. Khi viết trên Medium, nó hỗ trợ tải ảnh lên. Nó sẽ đăng ảnh lên

import * as fs from 'node:fs';
import * as http from 'node:http';
import * as path from 'node:path';

const PORT = 8000;

const MIME_TYPES = {
  default: 'application/octet-stream',
  html: 'text/html; charset=UTF-8',
  js: 'application/javascript; charset=UTF-8',
  css: 'text/css',
  png: 'image/png',
  jpg: 'image/jpg',
  gif: 'image/gif',
  ico: 'image/x-icon',
  svg: 'image/svg+xml',
};

const STATIC_PATH = path.join(process.cwd(), './static');

const toBool = [() => true, () => false];

const prepareFile = async (url) => {
  const paths = [STATIC_PATH, url];
  if (url.endsWith('/')) paths.push('index.html');
  const filePath = path.join(...paths);
  const pathTraversal = !filePath.startsWith(STATIC_PATH);
  const exists = await fs.promises.access(filePath).then(...toBool);
  const found = !pathTraversal && exists;
  const streamPath = found ? filePath : STATIC_PATH + '/404.html';
  const ext = path.extname(streamPath).substring(1).toLowerCase();
  const stream = fs.createReadStream(streamPath);
  return { found, ext, stream };
};

http.createServer(async (req, res) => {
  const file = await prepareFile(req.url);
  const statusCode = file.found ? 200 : 404;
  const mimeType = MIME_TYPES[file.ext] || MIME_TYPES.default;
  res.writeHead(statusCode, { 'Content-Type': mimeType });
  file.stream.pipe(res);
  console.log(`${req.method} ${req.url} ${statusCode}`);
}).listen(PORT);

console.log(`Server running at http://127.0.0.1:${PORT}/`);
5 và phản hồi chứa
import * as fs from 'node:fs';
import * as http from 'node:http';
import * as path from 'node:path';

const PORT = 8000;

const MIME_TYPES = {
  default: 'application/octet-stream',
  html: 'text/html; charset=UTF-8',
  js: 'application/javascript; charset=UTF-8',
  css: 'text/css',
  png: 'image/png',
  jpg: 'image/jpg',
  gif: 'image/gif',
  ico: 'image/x-icon',
  svg: 'image/svg+xml',
};

const STATIC_PATH = path.join(process.cwd(), './static');

const toBool = [() => true, () => false];

const prepareFile = async (url) => {
  const paths = [STATIC_PATH, url];
  if (url.endsWith('/')) paths.push('index.html');
  const filePath = path.join(...paths);
  const pathTraversal = !filePath.startsWith(STATIC_PATH);
  const exists = await fs.promises.access(filePath).then(...toBool);
  const found = !pathTraversal && exists;
  const streamPath = found ? filePath : STATIC_PATH + '/404.html';
  const ext = path.extname(streamPath).substring(1).toLowerCase();
  const stream = fs.createReadStream(streamPath);
  return { found, ext, stream };
};

http.createServer(async (req, res) => {
  const file = await prepareFile(req.url);
  const statusCode = file.found ? 200 : 404;
  const mimeType = MIME_TYPES[file.ext] || MIME_TYPES.default;
  res.writeHead(statusCode, { 'Content-Type': mimeType });
  file.stream.pipe(res);
  console.log(`${req.method} ${req.url} ${statusCode}`);
}).listen(PORT);

console.log(`Server running at http://127.0.0.1:${PORT}/`);
6 đã lưu của ảnh có thể được sử dụng để tạo URL CDN

Mặc dù tôi không biết ngôn ngữ lập trình mà Medium sử dụng để triển khai máy chủ tải lên, nhưng chúng tôi có thể sử dụng Node. js để triển khai máy chủ tải tệp lên

Trong bài viết này, chúng ta sẽ xem xét cách triển khai máy chủ tải tệp lên với mô-đun

import * as fs from 'node:fs';
import * as http from 'node:http';
import * as path from 'node:path';

const PORT = 8000;

const MIME_TYPES = {
  default: 'application/octet-stream',
  html: 'text/html; charset=UTF-8',
  js: 'application/javascript; charset=UTF-8',
  css: 'text/css',
  png: 'image/png',
  jpg: 'image/jpg',
  gif: 'image/gif',
  ico: 'image/x-icon',
  svg: 'image/svg+xml',
};

const STATIC_PATH = path.join(process.cwd(), './static');

const toBool = [() => true, () => false];

const prepareFile = async (url) => {
  const paths = [STATIC_PATH, url];
  if (url.endsWith('/')) paths.push('index.html');
  const filePath = path.join(...paths);
  const pathTraversal = !filePath.startsWith(STATIC_PATH);
  const exists = await fs.promises.access(filePath).then(...toBool);
  const found = !pathTraversal && exists;
  const streamPath = found ? filePath : STATIC_PATH + '/404.html';
  const ext = path.extname(streamPath).substring(1).toLowerCase();
  const stream = fs.createReadStream(streamPath);
  return { found, ext, stream };
};

http.createServer(async (req, res) => {
  const file = await prepareFile(req.url);
  const statusCode = file.found ? 200 : 404;
  const mimeType = MIME_TYPES[file.ext] || MIME_TYPES.default;
  res.writeHead(statusCode, { 'Content-Type': mimeType });
  file.stream.pipe(res);
  console.log(`${req.method} ${req.url} ${statusCode}`);
}).listen(PORT);

console.log(`Server running at http://127.0.0.1:${PORT}/`);
7 trong Node. js

Tạo một máy chủ HTTP với Node. js

Nodejs cung cấp module HTTP có thể dễ dàng sử dụng để tạo server, tất nhiên sẽ dễ dàng hơn nếu bạn sử dụng Koa hoặc Express. Mặc dù sử dụng các mô-đun gốc không hiệu quả nhưng nó có thể giúp chúng ta làm chủ Node tốt hơn. js. Nhưng nên sử dụng Koa hoặc Express trong môi trường sản xuất

Khi tạo máy chủ HTTP, chúng ta chỉ cần sử dụng API

import * as fs from 'node:fs';
import * as http from 'node:http';
import * as path from 'node:path';

const PORT = 8000;

const MIME_TYPES = {
  default: 'application/octet-stream',
  html: 'text/html; charset=UTF-8',
  js: 'application/javascript; charset=UTF-8',
  css: 'text/css',
  png: 'image/png',
  jpg: 'image/jpg',
  gif: 'image/gif',
  ico: 'image/x-icon',
  svg: 'image/svg+xml',
};

const STATIC_PATH = path.join(process.cwd(), './static');

const toBool = [() => true, () => false];

const prepareFile = async (url) => {
  const paths = [STATIC_PATH, url];
  if (url.endsWith('/')) paths.push('index.html');
  const filePath = path.join(...paths);
  const pathTraversal = !filePath.startsWith(STATIC_PATH);
  const exists = await fs.promises.access(filePath).then(...toBool);
  const found = !pathTraversal && exists;
  const streamPath = found ? filePath : STATIC_PATH + '/404.html';
  const ext = path.extname(streamPath).substring(1).toLowerCase();
  const stream = fs.createReadStream(streamPath);
  return { found, ext, stream };
};

http.createServer(async (req, res) => {
  const file = await prepareFile(req.url);
  const statusCode = file.found ? 200 : 404;
  const mimeType = MIME_TYPES[file.ext] || MIME_TYPES.default;
  res.writeHead(statusCode, { 'Content-Type': mimeType });
  file.stream.pipe(res);
  console.log(`${req.method} ${req.url} ${statusCode}`);
}).listen(PORT);

console.log(`Server running at http://127.0.0.1:${PORT}/`);
8 do mô-đun HTTP cung cấp và đồng thời liên kết một cổng

const http = require('http');
http.createServer((req, res) => {
res.end('hello world');
}).listen(4000);

Sau đó, chúng ta có thể kiểm tra nó và truy cập vào

import * as fs from 'node:fs';
import * as http from 'node:http';
import * as path from 'node:path';

const PORT = 8000;

const MIME_TYPES = {
  default: 'application/octet-stream',
  html: 'text/html; charset=UTF-8',
  js: 'application/javascript; charset=UTF-8',
  css: 'text/css',
  png: 'image/png',
  jpg: 'image/jpg',
  gif: 'image/gif',
  ico: 'image/x-icon',
  svg: 'image/svg+xml',
};

const STATIC_PATH = path.join(process.cwd(), './static');

const toBool = [() => true, () => false];

const prepareFile = async (url) => {
  const paths = [STATIC_PATH, url];
  if (url.endsWith('/')) paths.push('index.html');
  const filePath = path.join(...paths);
  const pathTraversal = !filePath.startsWith(STATIC_PATH);
  const exists = await fs.promises.access(filePath).then(...toBool);
  const found = !pathTraversal && exists;
  const streamPath = found ? filePath : STATIC_PATH + '/404.html';
  const ext = path.extname(streamPath).substring(1).toLowerCase();
  const stream = fs.createReadStream(streamPath);
  return { found, ext, stream };
};

http.createServer(async (req, res) => {
  const file = await prepareFile(req.url);
  const statusCode = file.found ? 200 : 404;
  const mimeType = MIME_TYPES[file.ext] || MIME_TYPES.default;
  res.writeHead(statusCode, { 'Content-Type': mimeType });
  file.stream.pipe(res);
  console.log(`${req.method} ${req.url} ${statusCode}`);
}).listen(PORT);

console.log(`Server running at http://127.0.0.1:${PORT}/`);
9

Kiểm tra máy chủ Node Js Tải tệp lên và lưu trên máy chủ

Chúng tôi có thể sử dụng biểu mẫu HTML để tải tệp lên và trong Nút. js, chúng ta có thể sử dụng gói busboy để phân tích dữ liệu biểu mẫu HTML đến. Nếu bạn muốn triển khai máy chủ tải tệp lên trong môi trường sản xuất, bạn nên sử dụng Multer (dựa vào busboy để phân tích dữ liệu biểu mẫu) hoặc

Chúng ta cần tối ưu hóa Node. js, trả lời biểu mẫu HTML khi truy cập đường dẫn gốc và tải tệp lên bằng đường dẫn

import * as fs from 'node:fs';
import * as http from 'node:http';
import * as path from 'node:path';
0

trong nút. js, khi nhận được tệp do máy khách tải lên, hãy sử dụng mô-đun busboy để phân tích cú pháp và lưu tệp vào thư mục hiện tại

Phần kết luận

Trong bài viết, chúng ta tìm hiểu về cách sử dụng Node. js để triển khai một máy chủ tải tệp lên rất đơn giản. Với mô-đun busboy, chúng ta có thể dễ dàng xử lý dữ liệu biểu mẫu HTML đến. Nhưng khuyên dùng Multer (dựa vào busboy để parse dữ liệu form) hay ghê

Bạn có muốn tìm hiểu cách phân tích cú pháp dữ liệu biểu mẫu HTML mà không cần sử dụng bất kỳ mô-đun npm nào không?

Thêm nội dung tại PlainEnglish. io. Đăng ký nhận bản tin hàng tuần miễn phí của chúng tôi. Theo dõi chúng tôi trên Twitter và LinkedIn. Kiểm tra Sự bất hòa trong cộng đồng của chúng tôi và tham gia Tập thể tài năng của chúng tôi

Bài viết này cung cấp một máy chủ tệp tĩnh đơn giản được xây dựng bằng Node thuần túy. js mà không cần sử dụng framework. Trạng thái hiện tại của Node. js sao cho hầu hết mọi thứ chúng tôi cần đều được cung cấp bởi các API sẵn có và chỉ một vài dòng mã

Ví dụ

Một máy chủ tệp tĩnh đơn giản được xây dựng bằng Node. js

import * as fs from 'node:fs';
import * as http from 'node:http';
import * as path from 'node:path';

const PORT = 8000;

const MIME_TYPES = {
  default: 'application/octet-stream',
  html: 'text/html; charset=UTF-8',
  js: 'application/javascript; charset=UTF-8',
  css: 'text/css',
  png: 'image/png',
  jpg: 'image/jpg',
  gif: 'image/gif',
  ico: 'image/x-icon',
  svg: 'image/svg+xml',
};

const STATIC_PATH = path.join(process.cwd(), './static');

const toBool = [() => true, () => false];

const prepareFile = async (url) => {
  const paths = [STATIC_PATH, url];
  if (url.endsWith('/')) paths.push('index.html');
  const filePath = path.join(...paths);
  const pathTraversal = !filePath.startsWith(STATIC_PATH);
  const exists = await fs.promises.access(filePath).then(...toBool);
  const found = !pathTraversal && exists;
  const streamPath = found ? filePath : STATIC_PATH + '/404.html';
  const ext = path.extname(streamPath).substring(1).toLowerCase();
  const stream = fs.createReadStream(streamPath);
  return { found, ext, stream };
};

http.createServer(async (req, res) => {
  const file = await prepareFile(req.url);
  const statusCode = file.found ? 200 : 404;
  const mimeType = MIME_TYPES[file.ext] || MIME_TYPES.default;
  res.writeHead(statusCode, { 'Content-Type': mimeType });
  file.stream.pipe(res);
  console.log(`${req.method} ${req.url} ${statusCode}`);
}).listen(PORT);

console.log(`Server running at http://127.0.0.1:${PORT}/`);

Phá vỡ

Các dòng sau nhập Nút nội bộ. mô-đun js

import * as fs from 'node:fs';
import * as http from 'node:http';
import * as path from 'node:path';

Tiếp theo chúng ta có một chức năng để tạo máy chủ.

import * as fs from 'node:fs';
import * as http from 'node:http';
import * as path from 'node:path';
1 trả về một đối tượng
import * as fs from 'node:fs';
import * as http from 'node:http';
import * as path from 'node:path';
2, mà chúng ta có thể bắt đầu bằng cách lắng nghe trên
import * as fs from 'node:fs';
import * as http from 'node:http';
import * as path from 'node:path';
3

http.createServer((req, res) => {
  /* handle http requests */
}).listen(PORT);

console.log(`Server running at http://127.0.0.1:${PORT}/`);

Hàm không đồng bộ

import * as fs from 'node:fs';
import * as http from 'node:http';
import * as path from 'node:path';
4 trả về cấu trúc.
import * as fs from 'node:fs';
import * as http from 'node:http';
import * as path from 'node:path';
5. Nếu tệp có thể được phân phối (quy trình máy chủ có quyền truy cập và không tìm thấy lỗ hổng truyền tải đường dẫn nào), chúng tôi sẽ trả về trạng thái HTTP của
import * as fs from 'node:fs';
import * as http from 'node:http';
import * as path from 'node:path';
6 dưới dạng
import * as fs from 'node:fs';
import * as http from 'node:http';
import * as path from 'node:path';
0 cho biết thành công (nếu không, chúng tôi trả về
import * as fs from 'node:fs';
import * as http from 'node:http';
import * as path from 'node:path';
1). Lưu ý rằng các mã trạng thái khác có thể được tìm thấy trong
import * as fs from 'node:fs';
import * as http from 'node:http';
import * as path from 'node:path';
2. Với trạng thái
import * as fs from 'node:fs';
import * as http from 'node:http';
import * as path from 'node:path';
3, chúng tôi sẽ trả về nội dung của tệp
import * as fs from 'node:fs';
import * as http from 'node:http';
import * as path from 'node:path';
4

Phần mở rộng của tệp đang được yêu cầu sẽ được phân tích cú pháp và viết thường. Sau đó, chúng tôi sẽ tìm kiếm bộ sưu tập

import * as fs from 'node:fs';
import * as http from 'node:http';
import * as path from 'node:path';
5 cho các loại MIME phù hợp. Nếu không tìm thấy kết quả phù hợp, chúng tôi sử dụng
import * as fs from 'node:fs';
import * as http from 'node:http';
import * as path from 'node:path';
6 làm loại mặc định

Cuối cùng nếu không có lỗi gì ta gửi file yêu cầu.

import * as fs from 'node:fs';
import * as http from 'node:http';
import * as path from 'node:path';
7 sẽ chứa một luồng
import * as fs from 'node:fs';
import * as http from 'node:http';
import * as path from 'node:path';
8 sẽ được dẫn vào
import * as fs from 'node:fs';
import * as http from 'node:http';
import * as path from 'node:path';
9 (một phiên bản của luồng
http.createServer((req, res) => {
  /* handle http requests */
}).listen(PORT);

console.log(`Server running at http://127.0.0.1:${PORT}/`);
0)

Làm cách nào để phân phối tệp trong NodeJS?

var static = require('node-static'); . Máy chủ)(__dirname); . createServer(function (req, res) { tập tin. serve(req, res); . .

Làm cách nào để chạy tệp NodeJS trên máy chủ?

Cách thông thường để chạy một Nút. js là chạy lệnh node có sẵn trên toàn cầu (sau khi bạn cài đặt Node. js) và chuyển tên tệp bạn muốn thực thi . Trong khi chạy lệnh, đảm bảo rằng bạn đang ở trong cùng thư mục chứa ứng dụng.

Hệ thống tệp trong NodeJS là gì?

Nút. js với tư cách là Máy chủ tệp . mô-đun hệ thống tệp js cho phép bạn làm việc với hệ thống tệp trên máy tính của mình . Để bao gồm mô-đun Hệ thống tệp, hãy sử dụng phương thức require(). var fs = yêu cầu('fs'); . đọc tập tin.

NodeJS có tốt cho máy chủ không?

Nút. js là môi trường thời gian chạy đa nền tảng, mã nguồn mở, đơn luồng để xây dựng các ứng dụng mạng và phía máy chủ nhanh và có thể mở rộng . Nó chạy trên công cụ thời gian chạy JavaScript V8 và nó sử dụng kiến ​​trúc I/O không chặn, hướng sự kiện, làm cho nó hiệu quả và phù hợp với các ứng dụng thời gian thực.