Node.js能否直接请求本地文件系统的PHP文件而非发起HTTP请求?
错误原因
postman-request 是专门用于发起HTTP/HTTPS网络请求的库,仅支持带协议前缀的标准URI地址(如http://xxx、https://xxx),你传入的本地相对文件路径不符合URI规范,因此抛出Invalid URI错误。
解决方案
根据你的实际需求选择对应方案即可:
方案1:通过HTTP请求获取PHP执行后的JSON结果
你的config.php属于现有PHP应用的一部分,要拿到它运行后输出的JSON内容,直接请求PHP服务对应的公开访问地址即可:
const request = require('postman-request'); // 替换为你本地PHP服务的实际访问地址,比如PHP应用跑在80端口就对应修改 const url = 'http://localhost/utils/config.php'; request(url, function (error, response, body) { console.log('error:', error); console.log('statusCode:', response && response.statusCode); // 直接将返回的JSON字符串转为JS对象使用 const config = JSON.parse(body); console.log('body:', config); });
方案2:本地直接调用PHP执行文件获取结果
如果不需要走Web服务,你可以用Node.js内置的child_process模块调用本地PHP CLI执行该文件,拿到输出结果:
const { exec } = require('child_process'); const path = require('path'); // 拼接config.php的绝对路径,避免相对路径匹配错误 const configPhpPath = path.join(__dirname, 'utils/config.php'); exec(`php ${configPhpPath}`, (error, stdout, stderr) => { if (error) { console.error(`执行出错: ${error.message}`); return; } if (stderr) { console.error(`PHP运行报错: ${stderr}`); return; } // stdout就是PHP输出的JSON内容 const config = JSON.parse(stdout); console.log('配置内容:', config); });
注意:该方案需要本地环境已安装PHP并配置了全局环境变量
方案3:仅读取config.php的源码内容
如果你不需要执行PHP,只是要读该文件的源码,直接用Node.js内置的fs模块即可,无需使用postman-request:
const fs = require('fs/promises'); const path = require('path'); const configPhpPath = path.join(__dirname, 'utils/config.php'); async function readConfigPhpCode() { try { const code = await fs.readFile(configPhpPath, 'utf-8'); console.log('config.php源码:', code); } catch (err) { console.error('读文件出错:', err); } } readConfigPhpCode();
内容的提问来源于stack exchange,提问作者JohnSmith
相关产品推荐
相关产品推荐

