source

fs.read File에서 데이터를 가져옵니다.

itover 2023. 1. 25. 08:34
반응형

fs.read File에서 데이터를 가져옵니다.

var content;
fs.readFile('./Index.html', function read(err, data) {
    if (err) {
        throw err;
    }
    content = data;
});
console.log(content);

로그undefined,왜요?

@Raynos가 말한 내용을 자세히 설명하자면, 정의한 함수는 비동기 콜백입니다.바로 실행되는 것이 아니라 파일 로딩이 완료되면 실행됩니다.readFile을 호출하면 제어가 즉시 반환되고 다음 줄의 코드가 실행됩니다.따라서 console.log를 호출할 때 콜백이 아직 호출되지 않았으며 이 콘텐츠는 아직 설정되지 않았습니다.비동기 프로그래밍에 오신 것을 환영합니다.

접근법 예시

const fs = require('fs');
// First I want to read the file
fs.readFile('./Index.html', function read(err, data) {
    if (err) {
        throw err;
    }
    const content = data;

    // Invoke the next step here however you like
    console.log(content);   // Put all of the code here (not the best solution)
    processFile(content);   // Or put the next step in a function and invoke it
});

function processFile(content) {
    console.log(content);
}

또, Raynos 의 예에 나타나 있듯이, 콜을 함수로 랩 해, 자신의 콜백을 건네주는 것이 좋습니다(이것은 분명히 베스트 프랙티스입니다).비동기식 콜을 콜백을 받는 기능으로 랩하는 습관을 들이면 번거로움과 코드를 많이 줄일 수 있을 것입니다.

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

비동기

fs.readFile(filename, [encoding], [callback])

파일의 전체 내용을 비동기적으로 읽습니다.예:

fs.readFile('/etc/passwd', function (err, data) {
  if (err) throw err;
  console.log(data);
});

콜백에는 2개의 인수(err, data)가 건네집니다.여기서 data는 파일의 내용입니다.

인코딩을 지정하지 않으면 raw 버퍼가 반환됩니다.


동기

fs.readFileSync(filename, [encoding])

fs.readFile의 동기 버전.filename이라는 이름의 파일의 내용을 반환합니다.

인코딩을 지정하면 이 함수는 문자열을 반환합니다.그렇지 않으면 버퍼가 반환됩니다.

var text = fs.readFileSync('test.md','utf8')
console.log (text)
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에서의 약속 사용

mz/fs에서의 비동기 사용

모듈은 코어 노드 라이브러리의 프로미스 버전을 제공합니다.사용법은 간단합니다.먼저 라이브러리 설치...

npm install mz

그러면...

const fs = require('mz/fs');
fs.readFile('./Index.html').then(contents => console.log(contents))
  .catch(err => console.error(err));

또는 비동기 함수로 쓸 수도 있습니다.

async function myReadfile () {
  try {
    const file = await fs.readFile('./Index.html');
  }
  catch (err) { console.error( err ) }
};

이 라인은 사용할 수 있습니다.

const content = fs.readFileSync('./Index.html', 'utf8');
console.log(content);
var data = fs.readFileSync('tmp/reltioconfig.json','utf8');

출력 표시를 버퍼로 인코딩하지 않고 파일을 동기 호출할 때 사용합니다.

말씀드렸듯이fs.readFile는 비동기 액션입니다.즉, 노드에게 파일을 읽도록 지시할 때 시간이 걸릴 수 있다는 점을 고려해야 하며, 그 사이 노드에서는 다음 코드가 계속 실행되었습니다.고객님의 경우:console.log(content);.

이것은 긴 여행을 위해 코드의 일부를 보내는 것과 같습니다(큰 파일을 읽는 것과 같습니다.

제가 쓴 댓글을 보세요.

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);

그래서...content로그를 기록할 때 아직 비어 있습니다. 노드가 아직 파일 내용을 검색하지 않았습니다.

는 이동함으로써 할 수 .console.log(content) 기능, 기능 ,content = data;을 읽을 때 content값을 가져옵니다.

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 += '\n' +  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!");
      });
    });
  }

빌트인 프로미스 라이브러리(노드 8+)를 사용하면, 이러한 낡은 콜백 기능을 보다 우아하게 할 수 있습니다.

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);
  }
}

sync 및 비동기 파일 읽기 방법:

//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에서 사용할 수 있습니다.

var path = "index.html"

const readFileAsync = fs.readFileSync(path, 'utf8');
// console.log(readFileAsync)

사용법readFileSync잘 먹히네요.

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());
});
var content;
fs.readFile('./Index.html', function read(err, data) {
    if (err) {
        throw err;
    }
    content = data;
});
console.log(content);

이는 노드가 비동기이며 읽기 기능을 기다리지 않고 프로그램이 시작되자마자 값을 정의되지 않은 것으로 콘솔링하기 때문입니다.이것은 콘텐츠 변수에 할당된 값이 없기 때문입니다.대처에는 약속, 발전기 등을 사용할 수 있습니다.이런 식으로 약속을 사용할 수 있습니다.

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.
})

다음은 기능하는 대상입니다.async, then을 채우다

const readFileAsync =  async (path) => fs.readFileSync(path, 'utf8');

파일을 읽을 수 있습니다.

var readMyFile = function(path, cb) {
      fs.readFile(path, 'utf8', function(err, content) {
        if (err) return cb(err, null);
        cb(null, content);
      });
    };

파일에 쓸 수 있습니다.

var createMyFile = (path, data, cb) => {
  fs.writeFile(path, data, function(err) {
    if (err) return console.error(err);
    cb();
  });
};

심지어 쇠사슬도 함께 묶어서

var readFileAndConvertToSentence = function(path, callback) {
  readMyFile(path, function(err, content) {
    if (err) {
      callback(err, null);
    } else {
      var sentence = content.split('\n').join(' ');
      callback(null, sentence);
    }
  });
};

대략적으로 말하면 기본적으로 비동기적인 node.js를 다루고 있습니다.

비동기라고 하는 것은 다른 것을 다루면서 정보나 데이터를 처리하거나 처리하는 것을 말합니다.이것은 평행과 동의어가 아니므로 주의해 주십시오.

고객님의 코드:

var content;
fs.readFile('./Index.html', function read(err, data) {
    if (err) {
        throw err;
    }
    content = data;
});
console.log(content);

샘플에서는 기본적으로 console.log 부분을 먼저 처리하므로 변수 'content'는 정의되지 않습니다.

출력을 정말로 필요로 하는 경우는, 대신에 다음과 같은 조작은 다음과 같습니다.

var content;
fs.readFile('./Index.html', function read(err, data) {
    if (err) {
        throw err;
    }
    content = data;
    console.log(content);
});

이것은 비동기입니다.익숙해지기는 어렵겠지만, 그런 것 같아요.다시 말씀드리지만 비동기란 무엇인가에 대한 대략적인 설명입니다.

fs-extra를 사용하는 것을 좋아합니다.모든 기능은 즉시 사용할 수 있기 때문입니다.await따라서 코드는 다음과 같습니다.

(async () => {
   try {
      const content = await fs.readFile('./Index.html');
      console.log(content);
   } catch (err) {
      console.error(err);
   }
})();

언급URL : https://stackoverflow.com/questions/10058814/get-data-from-fs-readfile

반응형