首页 > Web开发 > 详细

[Node.js] Read a File in Node.js with fs.readFile and fs.readFileSync

时间:2018-10-21 10:07:57      阅读:130      评论:0      收藏:0      [点我收藏+]

We‘ll read a csv file in node.js both synchronously, and asynchronously. The file we‘re reading is a plain text, utf8 file - but you can also use fs.readFile to read a binary file as a buffer. We‘ll look at the differences between readFile and readFileSync, and show examples of how to catch errors if they occur.

 

const fs = require(‘fs‘)

// Async:

fs.readFile(‘data.csv‘, ‘utf8‘, (err, data) => {
  console.log(data)
})


// Sync:

let results

try {
  // (invalid file error example)
  const data = fs.readFileSync(‘nofile.csv‘, ‘utf8‘)
  results = data  
} catch(e) {
  console.log("error", e)
}

console.log("results", results)

 

[Node.js] Read a File in Node.js with fs.readFile and fs.readFileSync

原文:https://www.cnblogs.com/Answer1215/p/9823937.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!