Get data from fs.readFile

前端 未结 15 2363
滥情空心
滥情空心 2020-11-22 15:38
var content;
fs.readFile(\'./Index.html\', function read(err, data) {
    if (err) {
        throw err;
    }
    content = data;
});
console.log(content);


        
相关标签:
15条回答
  • 2020-11-22 16:19
    const fs = require('fs')
    function readDemo1(file1) {
        return new Promise(function (resolve, reject) {
            fs.readFile(file1, 'utf8', function (err, dataDemo1) {
                if (err)
                    reject(err);
                else
                    resolve(dataDemo1);
            });
        });
    }
    async function copyFile() {
    
        try {
            let dataDemo1 = await readDemo1('url')
            dataDemo1 += '\n' +  await readDemo1('url')
    
            await writeDemo2(dataDemo1)
            console.log(dataDemo1)
        } catch (error) {
            console.error(error);
        }
    }
    copyFile();
    
    function writeDemo2(dataDemo1) {
        return new Promise(function(resolve, reject) {
          fs.writeFile('text.txt', dataDemo1, 'utf8', function(err) {
            if (err)
              reject(err);
            else
              resolve("Promise Success!");
          });
        });
      }
    
    0 讨论(0)
  • 2020-11-22 16:19

    Use the built in promisify library (Node 8+) to make these old callback functions more elegant.

    const fs = require('fs');
    const util = require('util');
    
    const readFile = util.promisify(fs.readFile);
    
    async function doStuff() {
      try {
        const content = await readFile(filePath, 'utf8');
        console.log(content);
      } catch (e) {
        console.error(e);
      }
    }
    
    0 讨论(0)
  • 2020-11-22 16:19
    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());
    });
    
    0 讨论(0)
  • 2020-11-22 16:22

    As said, fs.readFile is an asynchronous action. It means that when you tell node to read a file, you need to consider that it will take some time, and in the meantime, node continued to run the following code. In your case it's: console.log(content);.

    It's like sending some part of your code for a long trip (like reading a big file).

    Take a look at the comments that I've written:

    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);
    

    That's why content is still empty when you log it. node has not yet retrieved the file's content.

    This could be resolved by moving console.log(content) inside the callback function, right after content = data;. This way you will see the log when node is done reading the file and after content gets a value.

    0 讨论(0)
  • 2020-11-22 16:22

    you can read file by

    var readMyFile = function(path, cb) {
          fs.readFile(path, 'utf8', function(err, content) {
            if (err) return cb(err, null);
            cb(null, content);
          });
        };
    

    Adding on you can write to file,

    var createMyFile = (path, data, cb) => {
      fs.writeFile(path, data, function(err) {
        if (err) return console.error(err);
        cb();
      });
    };
    

    and even chain it together

    var readFileAndConvertToSentence = function(path, callback) {
      readMyFile(path, function(err, content) {
        if (err) {
          callback(err, null);
        } else {
          var sentence = content.split('\n').join(' ');
          callback(null, sentence);
        }
      });
    };
    
    0 讨论(0)
  • 2020-11-22 16:26

    To put it roughly, you're dealing with node.js which is asynchronous in nature.

    When we talk about async, we're talking about doing or processing info or data while dealing with something else. It is not synonymous to parallel, please be reminded.

    Your code:

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

    With your sample, it basically does the console.log part first, thus the variable 'content' being undefined.

    If you really want the output, do something like this instead:

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

    This is asynchronous. It will be hard to get used to but, it is what it is. Again, this is a rough but fast explanation of what async is.

    0 讨论(0)
提交回复
热议问题