var content; fs.readFile('./Index.html', function read(err, data) { if (err) { throw err; } content = data; }); console.log(content);
Logs undefined , why?(日志undefined ,为什么?)
undefined
To elaborate on what @Raynos said, the function you have defined is an asynchronous callback.(为了详细说明@Raynos所说的内容,您定义的函数是一个异步回调。)
const fs = require('fs'); var content; // First I want to read the file fs.readFile('./Index.html', function read(err, data) { if (err) { throw err; } content = data; // Invoke the next step here however you like console.log(content); // Put all of the code here (not the best solution) processFile(); // Or put the next step in a function and invoke it }); function processFile() { console.log(content); }
function doSomething (callback) { // any async callback invokes callback with response } doSomething (function doSomethingAfter(err, result) { // process the async result });
1.4m articles
1.4m replys
5 comments
57.0k users