nodejs - 创建简单服务端

Home / Article 百晓生 2021-11-3 2663

服务器上安装node.js,刚好要写一个简单的下载功能。记录!

在此之前,确保你已经安装了Node(并且你很会折腾) - 有人说,Java脚本和Java最本质的区别就是一个超会更新,一个死守旧。

如果你没有安装,请去官网下载并且安装:http://nodejs.cn/download/

中文文档:http://nodejs.cn/api/

先来说说node的优点以及缺点

粗略的来说node的优点即在于它是单线程、运行环境要求低,缺点同样明显的就是它一旦出现问题,全部瘫痪。

而php和java是多线程运行的,互不影响,但占资源高。

 

看一个小例子(随便写的,读取参数后返回下载地址,客户端使用地址下载即可。)

var http = require('http');
var url = require("url");
var querystring = require("querystring");
http.createServer(function(request, response) {
	//获取返回的url对象的query属性值 
	let arg = url.parse(request.url).query;
	//将arg参数字符串反序列化为一个对象
	let params = querystring.parse(arg);
	
    // 发送 HTTP 头部
    // HTTP 状态值: 200 : OK
    // 内容类型: text/plain
    response.writeHead(200, { 'Content-Type': 'text/plain' });
    // 发送响应数据 "Hello World"
    response.end(JSON.stringify(params));
}).listen(8080);

启动服务

[root@izbp17v35sjxegx358edr9z www]# node server.js
Server running at http://127.0.0.1:8080/

通过地址访问即可。

网上摘录例子,仅供参考

提供一个测试js代码..  浏览器通过get请求 http://127.0.0.1:20000/upload.do?filePath=XXXX即可触发上传过程

var express = require('express');
var url = require('url');
var fs = require('fs');
var http = require('http');
var queryString = require('querystring');
var bodyParser = require('body-parser');
 
var app = express();
 
app.use(bodyParser.json({limit:'1000kb'}));
app.use(bodyParser.urlencoded({limit:'1000kb',extended:true}));
 
var count=0;
 
app.get('/upload.do',function(req,resp){
 console.log('upload.do');
 //var path = url.parse(req.url).pathname;
 //console.log('Request for ' + path);
 var filePath = req.query.filePath;
 //var fileData = req.query.fileData;
 var address = req.query.address;
 
 upload(filePath,'127.0.0.1',20001);
 console.log('*** ' + ++count +' ***');
 var response = {
    "first":req.query.filePath,
    "last":req.query.address
  };
  resp.end(JSON.stringify(response));
});
 
function upload(filePath,address,port){
 
 var Data = readFile(filePath);
 var dataBase64 = Data.toString('base64');
 console.log(Data);
 console.log(dataBase64);
 //var DataJSON = JSON.stringify(Data);
 
 //fs.writeFile('D:/input.txt',dataBase64,function(err){
 // if(err){
 // console.err(err);
 // }
 //});
 var JsonData = queryString.stringify({
 filePath:filePath,
 fileData:dataBase64
 });
 //console.log(JsonData);
 var options = {
 method: "POST",
 host : address,
 port : port,
 path : '/upload.node',
 headers: {
  'Content-Type':'application/x-www-form-urlencoded'
 }
 };
 
 var req = http.request(options, function(res){
  res.setEncoding('utf8');
 });
 req.write(JsonData);
 req.end();
}
 
function readFile(filePath){
 var fileData = '';
 try{
 fileData = fs.readFileSync(filePath);
 }catch(e){
 fileData = '';
 }
 return fileData;
}
 
app.post('/download.do',function(req,resp){
 //可直接参考server.js的代码
})
 
var server = app.listen(20000,function(){
 
 console.log('Server started.');
})


本文链接:https://www.it72.com/12699.htm

推荐阅读
最新回复 (2)
  • 百晓生 2021-11-11
    引用 2
    #启动脚本
    node /usr/share/nginx/www/server.js &
    #结束脚本
    kill -9 $(netstat -nlp | grep :8080 | awk '{print $7}' | awk -F"/" '{ print $1 }')


  • MrLee 2021-11-12
    引用 3

    简单文件下载和API处理,node.js还是很强大,底层库支持的OK~~~

    const http = require('http');
    const url = require("url");
    const fs = require('fs');
    const path = require('path');
    const querystring = require("querystring");
    function fileExist(filepath) {
    	return new Promise(resolve => {
    		fs.access(filepath, (err) => {
    			if(err)resolve(false);
    			else resolve(true);
    		});
    	});
    }
    async function process (request, response) {
    	//获取返回的url对象的query属性值 
    	const {pathname, query} = url.parse(request.url);
    	//将arg参数字符串反序列化为一个对象
    	const params = querystring.parse(query);
    	if (pathname.startsWith('/download')) {
    		//下载文件
    		let filepath = path.resolve(__dirname, './upload/' + params['file']);
    		if(!await fileExist(filepath)) {
    			response.writeHead(404);
    			response.end('<!DOCTYPE html><html><head><meta charset="utf-8"><title>404</title></head></html>');
    			return;
    		}
    		fs.readFile(filepath,(err,data) => {
    			if (err) {
    				response.end(err);
    				return;
    			}
    			response.writeHead(200, {
    				'Content-Disposition': 'attachment; filename=' + params['file'],
    				'Content-type': 'application/octet-stream',
    				'Content-Length': data.length,
    				'Access-Control-Allow-Origin': '*',
    				'Access-Control-Allow-Headers': 'X-Requested-With',
    				'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS',
    			});
    			fs.createReadStream(filepath).pipe(response);
    		})
    	} else if (pathname.startsWith('/api')) {
    		// 发送 HTTP 头部
    		// HTTP 状态值: 200 : OK
    		// 内容类型: text/plain
    		let body = JSON.stringify({
    				code:'200',
    				msg:'success',
    				param:JSON.stringify(params),
    				path:pathname
    		});
    		response.writeHead(200, { 
    			'Content-Type': 'application/json',
    			'Content-Length': body.length, 
    		});
    		response.end(body);
    	} else {
    		let filepath = path.resolve(__dirname, './index.html');
    		if(!await fileExist(filepath)) {
    			response.writeHead(404);
    			response.end('<!DOCTYPE html><html><head><meta charset="utf-8"><title>404</title></head></html>');
    			return;
    		}
    		fs.readFile(filepath,(err,data) => {
    			if (err) {
    				response.end(err);
    				return;
    			}
    			response.writeHead(200, {
    				'Content-type': 'text/html; charset=utf-8',
    				'Content-Length': data.length
    			});
    			response.end(data);
    		})
    	}
    }
    http.createServer((request, response) => {try{process(request, response);}catch(error){console.log(error);}}).listen(8080);
    //http://www.xxx.com:8080/upload?file=notepad.txt


返回