var content;
fs.readFile('./Index.html', function read(err, data) {
if (err) {
throw err;
}
content = data;
});
console.log(content);
ログundefined
、なぜですか?
ベストアンサー1
@Raynos の発言を詳しく説明すると、定義した関数は非同期コールバックです。すぐに実行されるのではなく、ファイルの読み込みが完了したときに実行されます。readFile を呼び出すと、制御がすぐに返され、次のコード行が実行されます。したがって、console.log を呼び出すときには、コールバックはまだ呼び出されておらず、このコンテンツはまだ設定されていません。非同期プログラミングへようこそ。
アプローチの例
const fs = require('fs');
// First I want to read the file
fs.readFile('./Index.html', function read(err, data) {
if (err) {
throw err;
}
const content = data;
// Invoke the next step here however you like
console.log(content); // Put all of the code here (not the best solution)
processFile(content); // Or put the next step in a function and invoke it
});
function processFile(content) {
console.log(content);
}
あるいは、Raynos の例が示すように、呼び出しを関数でラップし、独自のコールバックを渡す方がよいでしょう。(どうやら、これがより良い方法のようです) 非同期呼び出しをコールバックを受け取る関数でラップする習慣を身に付けると、多くのトラブルや煩雑なコードが軽減されると思います。
function doSomething (callback) {
// any async callback invokes callback with response
}
doSomething (function doSomethingAfter(err, result) {
// process the async result
});