Read a file in Node.js

后端 未结 8 1118
礼貌的吻别
礼貌的吻别 2020-11-27 10:22

I\'m quite puzzled with reading files in Node.js.

fs.open(\'./start.html\', \'r\', function(err, fileToRead){
    if (!err){
        fs.readFile(fileToRead,         


        
8条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 11:04

    With Node 0.12, it's possible to do this synchronously now:

      var fs = require('fs');
      var path = require('path');
    
      // Buffer mydata
      var BUFFER = bufferFile('../public/mydata.png');
    
      function bufferFile(relPath) {
        return fs.readFileSync(path.join(__dirname, relPath)); // zzzz....
      }
    

    fs is the file system. readFileSync() returns a Buffer, or string if you ask.

    fs correctly assumes relative paths are a security issue. path is a work-around.

    To load as a string, specify the encoding:

    return fs.readFileSync(path,{ encoding: 'utf8' });
    

提交回复
热议问题