335
var content;
fs.readFile('./Index.html', function read(err, data) {
    if (err) {
        throw err;
    }
    content = data;
});
console.log(content);

ログundefined、なぜですか?

4

17 に答える 17

381

@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
});
于 2012-04-07T22:25:00.973 に答える
292

There is actually a Synchronous function for this:

http://nodejs.org/api/fs.html#fs_fs_readfilesync_filename_encoding

Asynchronous

fs.readFile(filename, [encoding], [callback])

Asynchronously reads the entire contents of a file. Example:

fs.readFile('/etc/passwd', function (err, data) {
  if (err) throw err;
  console.log(data);
});

The callback is passed two arguments (err, data), where data is the contents of the file.

If no encoding is specified, then the raw buffer is returned.


SYNCHRONOUS

fs.readFileSync(filename, [encoding])

Synchronous version of fs.readFile. Returns the contents of the file named filename.

If encoding is specified then this function returns a string. Otherwise it returns a buffer.

var text = fs.readFileSync('test.md','utf8')
console.log (text)
于 2012-12-29T04:15:49.920 に答える
124
function readContent(callback) {
    fs.readFile("./Index.html", function (err, content) {
        if (err) return callback(err)
        callback(null, content)
    })
}

readContent(function (err, content) {
    console.log(content)
})
于 2012-04-07T22:36:25.630 に答える
21
var data = fs.readFileSync('tmp/reltioconfig.json','utf8');

表示出力をバッファとしてエンコードせずに、ファイルを同期的に呼び出すためにこれを使用します。

于 2015-06-01T07:31:41.730 に答える
8

前述のとおりfs.readFile、非同期アクションです。ノードにファイルの読み込みを指示する場合、時間がかかることを考慮する必要があり、その間、ノードは次のコードを実行し続けました。あなたの場合は次のとおりconsole.log(content);です。

これは、長い旅行のためにコードの一部を送信するようなものです (大きなファイルの読み取りなど)。

私が書いたコメントを見てください:

var content;

// node, go fetch this file. when you come back, please run this "read" callback function
fs.readFile('./Index.html', function read(err, data) {
    if (err) {
        throw err;
    }
    content = data;
});

// in the meantime, please continue and run this console.log
console.log(content);

そのため、contentログに記録してもまだ空です。ノードはまだファイルのコンテンツを取得していません。

console.log(content)これは、コールバック関数内の の直後に移動することで解決できますcontent = data;。このようにして、ノードがファイルの読み取りを完了しcontent、値を取得した後にログが表示されます。

于 2014-04-11T21:23:49.490 に答える
5
var fs = require('fs');
var path = (process.cwd()+"\\text.txt");

fs.readFile(path , function(err,data)
{
    if(err)
        console.log(err)
    else
        console.log(data.toString());
});
于 2016-10-23T07:28:03.070 に答える
2

大まかに言えば、本質的に非同期である node.js を扱っています。

非同期について話すとき、何か他のことを処理しながら情報やデータを実行または処理することについて話しています。平行と同義ではありませんのでご注意ください。

あなたのコード:

var content;
fs.readFile('./Index.html', function read(err, data) {
    if (err) {
        throw err;
    }
    content = data;
});
console.log(content);

あなたのサンプルでは、​​基本的に console.log 部分を最初に実行するため、変数 'c​​ontent' は未定義です。

本当に出力が必要な場合は、代わりに次のようにします。

var content;
fs.readFile('./Index.html', function read(err, data) {
    if (err) {
        throw err;
    }
    content = data;
    console.log(content);
});

これは非同期です。慣れるのが大変でしょうが、それはそれです。繰り返しますが、これは非同期とは何かについての大まかな説明です。

于 2018-08-17T07:51:22.893 に答える
1

私はfs-extraを使用するのが好きです。なぜなら、すべての機能が箱から出してすぐに約束されるからですawait。したがって、コードは次のようになります。

(async () => {
   try {
      const content = await fs.readFile('./Index.html');
      console.log(content);
   } catch (err) {
      console.error(err);
   }
})();
于 2021-07-20T00:42:14.040 に答える