Get data from fs.readFile
1 2 3 4 5 6 7 8 | var content; fs.readFile('./Index.html', function read(err, data) { if (err) { throw err; } content = data; }); console.log(content); |
记录
为了详细说明@Raynos所说的内容,您定义的函数是一个异步回调。它不会立即执行,而是在文件加载完成后执行。当您调用readFile时,将立即返回控件并执行下一行代码。因此,当您调用console.log时,您的回调尚未被调用,并且此内容尚未设置。欢迎使用异步编程。
示例方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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); } |
或者更好的是,如Raynos的示例所示,将您的调用包装在一个函数中并传递您自己的回调。 (显然,这是更好的做法),我认为养成将异步调用包装在需要回调的函数中的习惯将为您节省很多麻烦和混乱的代码。
1 2 3 4 5 6 7 | function doSomething (callback) { // any async callback invokes callback with response } doSomething (function doSomethingAfter(err, result) { // process the async result }); |
实际上有一个同步功能:
http://nodejs.org/api/fs.html#fs_fs_readfilesync_filename_encoding
异步
异步读取文件的全部内容。例:
1 2 3 4 | fs.readFile('/etc/passwd', function (err, data) { if (err) throw err; console.log(data); }); |
回调传递了两个参数(err,data),其中data是文件的内容。
如果未指定编码,则返回原始缓冲区。
同步
fs.readFile的同步版本。返回名为filename的文件的内容。
如果指定了编码,则此函数返回一个字符串。否则,它将返回一个缓冲区。
1 2 | var text = fs.readFileSync('test.md','utf8') console.log (text) |
1 2 3 4 5 6 7 8 9 10 | 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) }) |
在ES7中使用Promises
与mz / fs异步使用
1 | npm install mz |
然后...
1 2 3 | const fs = require('mz/fs'); fs.readFile('./Index.html').then(contents => console.log(contents)) .catch(err => console.error(err)); |
或者,您可以用异步函数编写它们:
1 2 3 4 5 6 | async function myReadfile () { try { const file = await fs.readFile('./Index.html'); } catch (err) { console.error( err ) } }; |
1 | var data = fs.readFileSync('tmp/reltioconfig.json','utf8'); |
使用它来同步调用文件,
而不将其显示的输出编码为缓冲区。
这条线会工作,
1 2 | const content = fs.readFileSync('./Index.html', 'utf8'); console.log(content); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | 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 += ' ' + 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!"); }); }); } |
同步和异步文件读取方式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | //fs module to read file in sync and async way var fs = require('fs'), filePath = './sample_files/sample_css.css'; // this for async way /*fs.readFile(filePath, 'utf8', function (err, data) { if (err) throw err; console.log(data); });*/ //this is sync way var css = fs.readFileSync(filePath, 'utf8'); console.log(css); |
节点作弊可从read_file获得。
如前所述,
这就像发送一段较长的代码(例如读取一个大文件)一样。
看一下我写的评论:
1 2 3 4 5 6 7 8 9 10 11 12 | 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); |
这就是为什么
这可以通过在
使用内置的Promisify库(节点8+)可以使这些旧的回调函数更加美观。
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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); } } |
1 2 3 4 5 6 7 8 9 10 | 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()); }); |
1 2 3 4 5 6 7 8 | var content; fs.readFile('./Index.html', function read(err, data) { if (err) { throw err; } content = data; }); console.log(content); |
这仅仅是因为节点是异步的,并且它不会等待读取功能,并且程序一旦启动,它将把值定义为undefined,这实际上是正确的,因为没有为content变量分配值。
为了处理,我们可以使用promise,generator等。
我们可以通过这种方式使用诺言。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | new Promise((resolve,reject)=>{ fs.readFile('./index.html','utf-8',(err, data)=>{ if (err) { reject(err); // in the case of error, control flow goes to the catch block with the error occured. } else{ resolve(data); // in the case of success, control flow goes to the then block with the content of the file. } }); }) .then((data)=>{ console.log(data); // use your content of the file here (in this then). }) .catch((err)=>{ throw err; // handle error here. }) |
以下是该函数适用于
1 | const readFileAsync = async (path) => fs.readFileSync(path, 'utf8'); |
概括地说,您正在处理本质上是异步的node.js。
当我们谈论异步时,我们谈论的是在处理其他信息时处理或处理信息或数据。它不是parallel的同义词,请注意。
您的代码:
1 2 3 4 5 6 7 8 | var content; fs.readFile('./Index.html', function read(err, data) { if (err) { throw err; } content = data; }); console.log(content); |
对于您的示例,它基本上首先执行console.log部分,因此未定义变量" content"。
如果您确实想要输出,请执行以下操作:
1 2 3 4 5 6 7 8 | var content; fs.readFile('./Index.html', function read(err, data) { if (err) { throw err; } content = data; console.log(content); }); |
这是异步的。很难适应,但事实就是如此。
同样,这是对什么是异步的粗略但快速的解释。
您可以通过以下方式读取文件
1 2 3 4 5 6 | var readMyFile = function(path, cb) { fs.readFile(path, 'utf8', function(err, content) { if (err) return cb(err, null); cb(null, content); }); }; |
加上您可以写入文件,
1 2 3 4 5 6 | var createMyFile = (path, data, cb) => { fs.writeFile(path, data, function(err) { if (err) return console.error(err); cb(); }); }; |
甚至连在一起
1 2 3 4 5 6 7 8 9 10 11 | var readFileAndConvertToSentence = function(path, callback) { readMyFile(path, function(err, content) { if (err) { callback(err, null); } else { var sentence = content.split(' ').join(' '); callback(null, sentence); } }); }; |