最近nginx有需求实现上传feat,惊喜发现已经支持js了,因此尝试使用js实现上传。

  1. 为了支持njs需要模块加载
  2. 具体使用js业务模块,需要使用js相关指令
  3. load_module指令需要放在全局即default.conf

例子如下

load_module modules/ngx_http_js_module.so;

events { }


http {

# 这里就不再限制了,nginx默认为1MB
client_max_body_size 0;

js_path "/etc/nginx/njs/";

js_import main from upload.js;

server {

...
location /upload-cert {
js_content main.resolve;
}
...
}
  • njs只是js子集,因此语法及功能也都是有限的
const fs = require('fs');
const crypto = require('crypto');
const dest = `/var/www/ssl`;

function writeFile(fileContent, fileSuffix) {
let fileName = `${crypto.createHash('md5').update(fileContent).digest("hex")}.${fileSuffix || 'crt'}`;
fs.writeFileSync(`${dest}/${fileName}`, fileContent);
return fileName;
}

function upload(r) {
let body = JSON.parse(r.requestBody);
r.return(200, JSON.stringify({
crtFileName: writeFile(body.crtFile), keyFileName: writeFile(body.keyFile, 'key'),
}));
}

function main(r) {
upload(r);
}

export default {resolve: main}

--

--

--

Develop with pleasure!

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Alan He

Alan He

Develop with pleasure!

More from Medium

How To Limit Battery Charging (Set A Charge Threshold) For ASUS Laptops On Linux

Uninstall MySQL and Install MariaDB 10.7 on Ubuntu 18.04

Nginx Reverse proxy for Multiple Servers

Install LibreOffice 7.3 on Ubuntu / Rocky Linux & Fedora

Install LibreOffice 7.3 on Ubuntu / Rocky Linux & Fedora