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 //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 //127.0.0.1:${PORT}/`];
6 đã lưu của ảnh có thể được sử dụng để tạo URL CDNMặ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 //127.0.0.1:${PORT}/`];
7 trong Node. jsTạo một máy chủ HTTP với Node. jsNodejs 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 //127.0.0.1:${PORT}/`];
8 do mô-đun HTTP cung cấp và đồng thời liên kết một cổngconst 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 //127.0.0.1:${PORT}/`];
9Kiể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';
0trong 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 //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';
3http.createServer[[req, res] => {
/* handle http requests */
}].listen[PORT];
console.log[`Server running at //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';
4Phầ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 địnhCuố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 //127.0.0.1:${PORT}/`];
0]