開始要求()使用函式和檔案

Require 是一個語句,Node 在某種意義上解釋為 getter 函式。例如,假設你有一個名為 analysis.js 的檔案,並且檔案內部如下所示,

function analyzeWeather(weather_data) {
  console.log('Weather information for ' + weather_data.time + ': ');
  console.log('Rainfall: ' + weather_data.precip);
  console.log('Temperature: ' + weather_data.temp);
  //More weather_data analysis/printing...
}

該檔案僅包含方法 analyzeWeather(weather_data)。如果我們想要使用這個函式,它必須在這個檔案中使用,或者複製到它想要使用的檔案中。但是,Node 包含了一個非常有用的工具來幫助程式碼和檔案組織,這是模組

為了利用我們的功能,我們必須首先通過一個宣告來開始這個功能。我們的新檔案看起來像這樣,

module.exports = {
  analyzeWeather: analyzeWeather
}
function analyzeWeather(weather_data) {
  console.log('Weather information for ' + weather_data.time + ': ');
  console.log('Rainfall: ' + weather_data.precip);
  console.log('Temperature: ' + weather_data.temp);
  //More weather_data analysis/printing...
}

使用這個小的 module.exports 語句,我們的函式現在可以在檔案之外使用了。剩下要做的就是使用 require()

require 提供函式或檔案時,語法非常相似。它通常在檔案的開頭完成,並設定為 varconst ,以便在整個檔案中使用。例如,我們有另一個檔案(與 analyze.js 相同的級別,名為 handleWeather.js,如下所示,

const analysis = require('./analysis.js');

weather_data = {
  time: '01/01/2001',
  precip: 0.75,
  temp: 78,
  //More weather data...
};
analysis.analyzeWeather(weather_data);

在這個檔案中,我們使用 require() 來獲取我們的 analysis.js 檔案。使用時,我們只需呼叫分配給此 require 的變數或常量,並使用匯出的內部函式。