In Node.js mode, changed it to use Node.js' built-in fetch method if available.

And this may also solve issue #11.
main 2.7.5
zboris12 2025-09-13 20:13:00 +09:00
parent 275086489d
commit 66bec77187
5 changed files with 172 additions and 96 deletions

View File

@ -4,11 +4,6 @@
function supplyZgaUrlFetch(z){ function supplyZgaUrlFetch(z){
//Only for nodejs Start// //Only for nodejs Start//
const m_urlparser = require("url");
const m_h = {
"http:": require('follow-redirects').http,
"https:": require('follow-redirects').https,
};
// @type {boolean} // @type {boolean}
z.isNode = function(){return this === globalThis.global;}(); z.isNode = function(){return this === globalThis.global;}();
//Only for nodejs End// //Only for nodejs End//
@ -23,63 +18,107 @@ z.isBrowser = function(){return this === globalThis.self;}();
*/ */
z.urlFetch = function(url, params){ z.urlFetch = function(url, params){
/**
* @return {Promise<Uint8Array>}
*/
var fetchfunc = async function(){
/** @type {!RequestInit} */
var reqinf = {
method: "GET",
redirect: "follow",
};
if(params){
if(params.payload){
reqinf.body = params.payload;
}
if(params.headers){
reqinf.headers = params.headers;
}
if(params.method){
reqinf.method = params.method;
}
}
/** @type {Response} */
var resp = await fetch(url, reqinf);
if(resp.ok){
/** @type {ArrayBuffer} */
var abdat = await resp.arrayBuffer();
return new Uint8Array(abdat);
}else{
/** @type {string} */
var msg = await resp.text();
throw new Error("Fetch failed." + resp.status + ": " + msg);
}
};
//Only for nodejs Start// //Only for nodejs Start//
if(z.isNode){ if(z.isNode){
return new Promise(function(resolve, reject){ if(globalThis.fetch){
// @type {URL} console.log("Use built in fetch.");
var opts = m_urlparser.parse(url); return fetchfunc();
var http = m_h[opts.protocol]; }else{
// @type {string|Buffer} console.log("Use http module.");
var dat = null; const m_urlparser = require("url");
var encoding = undefined; const m_h = {
opts.method = "GET"; "http:": require('follow-redirects').http,
if(params){ "https:": require('follow-redirects').https,
if(params.payload instanceof Buffer){ };
dat = params.payload; return new Promise(function(resolve, reject){
}else if(params.payload instanceof Uint8Array){ // @type {URL}
dat = Buffer.from(params.payload.buffer); var opts = m_urlparser.parse(url);
}else if(params.payload instanceof ArrayBuffer){ var http = m_h[opts.protocol];
dat = Buffer.from(params.payload); // @type {string|Buffer}
}else{ var dat = null;
dat = params.payload; var encoding = undefined;
encoding = "binary"; opts.method = "GET";
if(params){
if(params.payload instanceof Buffer){
dat = params.payload;
}else if(params.payload instanceof Uint8Array){
dat = Buffer.from(params.payload.buffer);
}else if(params.payload instanceof ArrayBuffer){
dat = Buffer.from(params.payload);
}else{
dat = params.payload;
encoding = "binary";
}
if(params.headers){
opts.headers = params.headers;
}
if(params.method){
opts.method = params.method;
}
if(params.validateHttpsCertificates === false){
opts.rejectUnauthorized = false;
}
} }
if(params.headers){
opts.headers = params.headers;
}
if(params.method){
opts.method = params.method;
}
if(params.validateHttpsCertificates === false){
opts.rejectUnauthorized = false;
}
}
// @type {http.ClientRequest} // @type {http.ClientRequest}
var hreq = http.request(opts, function(a_res){ // @type {http.IncomingMessage} a_res var hreq = http.request(opts, function(a_res){ // @type {http.IncomingMessage} a_res
if(a_res.statusCode !== 200){ if(a_res.statusCode !== 200){
var a_err = new Error("Failed to request url. " + url + "\n Status Code: " + a_res.statusCode); var a_err = new Error("Failed to request url. " + url + "\n Status Code: " + a_res.statusCode);
a_res.resume(); a_res.resume();
throw a_err;
}
// @type {Array<Buffer>}
var a_bufs = [];
var a_bufs_len = 0;
a_res.on("data", function(b_chunk){ // @type {Buffer} b_chunk
a_bufs.push(b_chunk);
a_bufs_len += b_chunk.length;
});
a_res.on("end", function(){
// @type {Buffer}
var b_bdat = Buffer.concat(a_bufs, a_bufs_len);
resolve(b_bdat);
});
});
hreq.on("error", function(a_err){
throw a_err; throw a_err;
}
// @type {Array<Buffer>}
var a_bufs = [];
var a_bufs_len = 0;
a_res.on("data", function(b_chunk){ // @type {Buffer} b_chunk
a_bufs.push(b_chunk);
a_bufs_len += b_chunk.length;
});
a_res.on("end", function(){
// @type {Buffer}
var b_bdat = Buffer.concat(a_bufs, a_bufs_len);
resolve(b_bdat);
}); });
hreq.end(dat, encoding);
}); });
hreq.on("error", function(a_err){ }
throw a_err;
});
hreq.end(dat, encoding);
});
} }
//Only for nodejs End// //Only for nodejs End//
@ -94,39 +133,7 @@ z.urlFetch = function(url, params){
// browser // browser
if(z.isBrowser && globalThis.self.fetch){ if(z.isBrowser && globalThis.self.fetch){
/** return fetchfunc();
* @return {Promise<Uint8Array>}
*/
var func = async function(){
/** @type {!RequestInit} */
var reqinf = {
method: "GET",
redirect: "follow",
};
if(params){
if(params.payload){
reqinf.body = params.payload;
}
if(params.headers){
reqinf.headers = params.headers;
}
if(params.method){
reqinf.method = params.method;
}
}
/** @type {Response} */
var resp = await fetch(url, reqinf);
if(resp.ok){
/** @type {ArrayBuffer} */
var abdat = await resp.arrayBuffer();
return new Uint8Array(abdat);
}else{
/** @type {string} */
var msg = await resp.text();
throw new Error("Fetch failed." + resp.status + ": " + msg);
}
};
return func();
} }
return null; return null;
}; };

View File

@ -1,8 +1,3 @@
const m_urlparser = require("url");
const m_h = {
"http:": require('follow-redirects').http,
"https:": require('follow-redirects').https,
};
const z = require("./zgaindex.js"); const z = require("./zgaindex.js");
z.forge = require("node-forge"); z.forge = require("node-forge");
z.PDFLib = require("pdf-lib"); z.PDFLib = require("pdf-lib");

View File

@ -1,6 +1,6 @@
{ {
"name": "zgapdfsigner", "name": "zgapdfsigner",
"version": "2.7.3", "version": "2.7.5",
"author": "zboris12", "author": "zboris12",
"description": "A javascript tool to sign a pdf or set protection to a pdf in web browser, Google Apps Script and nodejs.", "description": "A javascript tool to sign a pdf or set protection to a pdf in web browser, Google Apps Script and nodejs.",
"homepage": "https://github.com/zboris12/zgapdfsigner", "homepage": "https://github.com/zboris12/zgapdfsigner",
@ -32,7 +32,9 @@
], ],
"scripts": { "scripts": {
"build": "./build.sh", "build": "./build.sh",
"test": "node test4node.js ${pfxpwd}" "server": "node test4node.js webserver",
"test": "node test4node.js ${pfxpwd}",
"test2": "node test4node.js fetch"
}, },
"dependencies": { "dependencies": {
"follow-redirects": "1.15.6", "follow-redirects": "1.15.6",

View File

@ -81,6 +81,7 @@ async function testMe(){
sopt = { sopt = {
p12cert: pfx, p12cert: pfx,
pwd: ps, pwd: ps,
// signdate: "/1",
permission: parseInt(document.getElementById("sperm").value), permission: parseInt(document.getElementById("sperm").value),
reason: document.getElementById("tReason").value, reason: document.getElementById("tReason").value,
location: document.getElementById("tLocation").value, location: document.getElementById("tLocation").value,
@ -189,6 +190,22 @@ function changeSperm(){
break; break;
} }
} }
// test urlFetch
async function main2(){
/** @type {Uint8Array} */
var u8arr = await Zga.urlFetch("http://localhost:8080", {
"headers": {
"testzb": "orange"
}
});
// /** @type {string} */
// var str = btoa(Zga.u8arrToRaw(u8arr));
/** @type {TextDecoder} */
var txtdec = new TextDecoder('utf-8');
/** @type {string} */
var str = txtdec.decode(u8arr);
console.log(str);
}
</script> </script>
<style> <style>
body { body {

View File

@ -187,6 +187,55 @@ async function main1(angle){
console.log("Done"); console.log("Done");
} }
// test urlFetch
async function main2(){
/** @type {Uint8Array} */
var u8arr = await Zga.urlFetch("http://localhost:8080", {
"headers": {
"testzb": "pineapple"
}
});
// /** @type {string} */
// var str = btoa(Zga.u8arrToRaw(u8arr));
/** @type {TextDecoder} */
var txtdec = new TextDecoder("utf-8");
/** @type {string} */
var str = txtdec.decode(u8arr);
console.log(str);
}
function webserver(){
require("http").createServer(function(req, res){
if(req.method == "GET"){
if(req.headers["testzb"]){
res.setHeader("Access-Control-Allow-Origin", "*");
if(req.url == "/"){
console.log(req.headers["testzb"]);
res.writeHead(302, {"Location": "/testzb"});
res.end();
}else if(req.url == "/testzb"){
res.writeHead(200, {"Content-Type": "text/plain"});
res.end("I am redirected!\n");
}else{
res.statusCode = 500;
res.statusMessage = "Bad Request.";
res.end();
}
}else{
res.writeHead(200, {"Content-Type": "text/plain"});
res.end("Hello World\n");
}
}else if(req.method == "OPTIONS"){
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Method", "GET, OPTIONS, HEAD");
res.setHeader("Access-Control-Allow-Headers", "Accept, Accept-Language, Content-Language, Content-Type, Range, testzb");
res.statusCode = 200;
res.statusMessage = "CORS OK";
res.end();
}
}).listen(8080, function(){console.log("Server http://localhost:8080")});
}
async function main(){ async function main(){
/** @type {Array<number>} */ /** @type {Array<number>} */
var arr = [0, 90, 180, 270]; var arr = [0, 90, 180, 270];
@ -197,4 +246,10 @@ async function main(){
} }
} }
main(); if(process.argv[2] == "webserver"){
webserver();
}else if(process.argv[2] == "fetch"){
main2();
}else{
main();
}