lastleaf / node-fastcgi-client Goto Github PK
View Code? Open in Web Editor NEWA FastCGI client implementation in Node.js, mostly designed for cummunication with PHP.
A FastCGI client implementation in Node.js, mostly designed for cummunication with PHP.
看不懂咋用的
node-fastcgi-client/lib/request.js
Line 177 in fadbd33
您好,我准备将我的 PHP 程序升级为 NodeJS,思路是使用 express 框架通过一个中间件将某些请求转发至 PHP-FPM处理,新的API交友NodeJS处理。但是在转发 HTTP 请求过程中,由于某些 HTTP 包体过大,底层会使用多个 TCP 包来发送,所以 stdin._write
会被调用多次,这样的话, stdin._write
中的 cb
就会被调用多次,然后系统就报错了:
_stream_writable.js:456
throw new ERR_MULTIPLE_CALLBACK();
^
Error [ERR_MULTIPLE_CALLBACK]: Callback called multiple times
at onwrite (_stream_writable.js:456:11)
at afterWrite (_stream_writable.js:485:3)
at processTicksAndRejections (internal/process/next_tick.js:76:17)
这是我写的 express 中间件代码,请帮忙解答一下疑问,感激不尽
const path = require('path');
const fastCGIClient = require('fastcgi-client');
const defaultOptions = {
host: '127.0.0.1',
port: 9000,
documentRoot: path.dirname(require.main.filename || '.'),
skipCheckServer: true,
};
module.exports = function(options = {}, input_fastcgi_params = {}) {
options = Object.assign({}, defaultOptions, options);
const fpm = new Promise((resolve, reject) => {
const loader = fastCGIClient(options);
loader.on('ready', () => resolve(loader));
loader.on('error', reject);
});
return async function(req, res, next) {
// 以 /api/node 开始的请求全部由 express 处理
if (req.url.startsWith('/api/node')) {
return next();
}
let [_, ...queryString] = req.url.split('?');
queryString = queryString ? queryString[0] : '';
let fastcgi_params = Object.assign({}, input_fastcgi_params, {
REQUEST_URI: `/index.php${req.url}`,
DOCUMENT_URI: '/index.php',
SCRIPT_NAME: '/index.php',
QUERY_STRING: queryString,
REQUEST_METHOD: req.method,
CONTENT_TYPE: req.headers['content-type'],
CONTENT_LENGTH: req.headers['content-length'],
SERVER_PROTOCOL: 'HTTP/1.1',
REQUEST_SCHEME: req.protocol,
HTTPS: req.protocol === 'https' ? 'on': undefined,
GATEWAY_INTERFACE: 'CGI/1.1',
SERVER_SOFTWARE: 'PHP-FPM FOR Node',
REMOTE_ADDR: req.connection.remoteAddress,
REMOTE_PORT: req.connection.remotePort,
SERVER_NAME: req.connection.domain,
REDIRECT_STATUS: 200,
// 下面的由外部传入
// SERVER_ADDR: 127.0.0.1,
// SERVER_PORT: 8080,
// DOCUMENT_ROOT: /var/www/public
// SCRIPT_FILENAME: /var/www/public/index.php
});
if (! fastcgi_params.REQUEST_URI || ! fastcgi_params.REQUEST_URI.startsWith('/')) {
throw new Error('Invalid URI');
}
for (const fastcgi_param in fastcgi_params) {
if (typeof fastcgi_params[fastcgi_param] === 'undefined') {
delete fastcgi_params[fastcgi_param];
}
}
console.log(fastcgi_params);
const phpFPM = await fpm;
return new Promise(function(resolve, reject) {
phpFPM.request(fastcgi_params, function(err, request) {
if (err) return reject(err);
var output = '';
var errors = '';
// console.log(req.body);
// console.log(req.files.file);
req.on('end', function(){
console.log('没有数据了');
});
req.on('data', function(chunk) {
// console.log(chunk.toString());
console.log(`接收到 ${chunk.length} 个字节的数据`);
request.stdin.write(chunk, null, null);
});
// request.stdin.on('pipe', function(src) {
// console.error('有数据正通过管道流入写入器');
// });
request.stdout.on('data', function(data) {
output += data.toString('utf-8');
});
request.stderr.on('data', function(data) {
errors += data.toString('utf-8');
});
request.stdout.on('end', function() {
if (errors) {
return reject(new Error(errors));
}
const head = output.match(/^[\s\S]*?\r\n\r\n/)[0];
const parseHead = head.split('\r\n').filter(_ => _);
const responseHeaders = {};
let statusCode = 200;
let statusMessage = '';
for (const item of parseHead) {
const pair = item.split(': ');
if (pair.length > 1 && pair[0] && pair[1]) {
if (pair[0] in responseHeaders) {
responseHeaders[pair[0]].push(pair[1]);
} else {
responseHeaders[pair[0]] = [pair[1]];
}
if (pair[0] === 'Status') {
const match = pair[1].match(/(\d+) (.*)/);
statusCode = parseInt(match[1]);
statusMessage = match[2];
}
}
}
res.writeHead(statusCode, statusMessage, responseHeaders);
const body = output.slice(head.length);
res.write(body);
res.end();
resolve({ fastcgi_params, body });
});
});
});
};
};
Hi,
I have my php-fpm running on 127.0.0.1:9000 but when running "npm test" i am getting error-
"uncaught assertion error file not found-helloworld"
I have file helloworld file in www folder of node-fastcgi-client but still getting the error
Hi,
Thanks for your great work. I've created a project based on your work. But I noticed that the code on npm is not the latest. Please publish the latest code to npm, so that it supports the sockFile option.
Regards,
Chunlong
node-fastcgi-client/lib/request.js
Line 177 in fadbd33
I use the HTTP_COOKIE params that i can get cookie in php, but i can't set cookie in php. so how to support this function
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.