Javascript 如何在 Node.js 中同步读取文件内容?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34135302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:56:55  来源:igfitidea点击:

How to read the content of files synchronously in Node.js?

javascriptnode.jsfs

提问by alexchenco

This is what I have:

这就是我所拥有的:

#! /usr/bin/env node

var fs = require('fs'),
    files = fs.readdirSync(__dirname + '/files/'),

files.forEach(function(file) {
  fs.readFile(__dirname + '/files/' + file, 'utf8', function (error, data) {
    console.log(data)
  })
})

Even though I'm using readdirSyncthe output is still asynchronous:

即使我使用readdirSync的输出仍然是异步的:

alex@alex-K43U:~/node/readFiles$ node index.js 
foo 1

foo 3

foo 2

How to modify the code so the output becomes synchronous?

如何修改代码使输出同步?

alex@alex-K43U:~/node/readFiles$ node index.js 
foo 1

foo 2

foo 3

回答by Gazler

You need to use readFileSync, your method is still reading the files asynchronously, which can result in printing the contents out of order depending on when the callback happens for each read.

您需要使用readFileSync,您的方法仍在异步读取文件,这可能会导致内容乱序打印,具体取决于每次读取的回调发生时间。

var fs = require('fs'),
    files = fs.readdirSync(__dirname + '/files/');

files.forEach(function(file) {
  var contents = fs.readFileSync(__dirname + '/files/' + file, 'utf8');
  console.log(contents);
})

回答by Peter Paul Kiefer

That's because you read the file asynchronously. Try:

那是因为您异步读取文件。尝试:

#! /usr/bin/env node

var fs = require('fs'),
    files = fs.readdirSync(__dirname + '/files/'),

files.forEach(function(file) {
  var data = fs.readFileSync(__dirname + '/files/' + file, 'utf8');
  console.log(data);
});

NodeJS Documentation for 'fs.readFileSync()'

'fs.readFileSync()' 的 NodeJS 文档

回答by Daniel A. White

Have you seen readFileSync? I think that could be your new friend.

你见过readFileSync吗?我想那可能是你的新朋友。