Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

javascript - 从fs.readFile获取数据(Get data from fs.readFile)

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

Logs undefined , why?(日志undefined ,为什么?)

  ask by karaxuna translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To elaborate on what @Raynos said, the function you have defined is an asynchronous callback.(为了详细说明@Raynos所说的内容,您定义的函数是一个异步回调。)

It doesn't execute right away, rather it executes when the file loading has completed.(它不会立即执行,而是在文件加载完成后执行。) When you call readFile, control is returned immediately and the next line of code is executed.(当您调用readFile时,将立即返回控件并执行下一行代码。) So when you call console.log, your callback has not yet been invoked, and this content has not yet been set.(因此,当您调用console.log时,您的回调尚未被调用,并且此内容尚未设置。) Welcome to asynchronous programming.(欢迎使用异步编程。) Example approaches(示例方法) 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); } Or better yet, as Raynos example shows, wrap your call in a function and pass in your own callbacks.(或者更好的是,如Raynos的示例所示,将您的调用包装在一个函数中并传递您自己的回调。) (Apparently this is better practice) I think getting into the habit of wrapping your async calls in function that takes a callback will save you a lot of trouble and messy code.((显然,这是一种更好的做法),我认为养成将异步调用包装在需要回调的函数中的习惯将为您节省很多麻烦和混乱的代码。) function doSomething (callback) { // any async callback invokes callback with response } doSomething (function doSomethingAfter(err, result) { // process the async result });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...