【发布时间】:2023-03-04 07:21:06
【问题描述】:
我是 Node 新手。
我将一堆前端函数从我的库中移到了一个新的 Node.js 库中。
我知道你必须把它放在 module.exports = {
并且所有的函数都必须是这种格式: tempToFahrenheit:函数(tempInC){
我可以正常调用其他脚本中的函数,但函数相互调用时遇到问题:
tempToFahrenheit: function(tempInC){
tempInF = (tempInC*1.8)+32;
return tempInF;
},
getTextWeatherUsingStationUsingRequest: function(theStation){
const http = require("http");
const https = require("https");
// theURL = 'https://api.weather.gov/stations/' + theStation + '/observations/current';
thePath = '/stations/' + theStation + '/observations/current';
function requestTheData(){
var returnedJSON;
var options = {
protocol: "https:",
hostname: "api.weather.gov",
path: thePath,
method: "GET",
headers: {
'Accept' : 'application/json',
'Content-Type': 'application/json',
'User-Agent' : 'MY-TEST-UA'
}
};
var req= https.request(options);
var theData = '';
req.on("response", function(res){
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
theData += chunk;
});
res.on('end', () => {
console.log('No more data in response.');
returnedJSON = JSON.parse(theData);
console.log(returnedJSON.id);
// Why can't ot find temptoFahrenheit
theTemp = Math.round( tempToFahrenheit(returnedJSON.properties.temperature.value) )
windSpeed = Math.round(returnedJSON.properties.windSpeed.value);
pressure = returnedJSON.properties.barometricPressure.value;
在此文本上方,您会看到一行尝试在函数 getTextWeatherUsingStationUsingRequest() 中调用 tempToFahrenheit()。我该如何做到这一点?您必须为 Node.js 设置函数的奇怪方式(哈希对吗?)这些函数似乎无法相互访问。
另一个更一般的问题。 Node.js 的好处应该是您在前端和后端使用 Javascript,并且您可以重用代码,就像在库中一样。但正如我们在这里看到的那样,我必须对代码进行相当大的(并且容易出错)更改才能使其与 Node.js 一起使用。另外,我必须保留该库的两份副本,一份是前端,另一份是 Node.js。在 Node 中做库没有更好的方法吗?
【问题讨论】:
-
你是在一个对象中声明这些函数吗?
{ tempToFahrenheit: ..., otherfunction : ..}? -
@GeorgeBailey 是 module.exports = { tempToFahrenheit: ..., otherfunction : ..}
标签: javascript node.js