如何在Node.js中同步读取文件内容? [英] How to read the content of files synchronously in Node.js?

查看:78
本文介绍了如何在Node.js中同步读取文件内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我所拥有的:

#! /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)
  })
})

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

Even though I'm using readdirSync the output is still asynchronous:

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


推荐答案

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

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.

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

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

这篇关于如何在Node.js中同步读取文件内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆