Programing

fs.readFile에서 데이터 가져 오기

lottogame 2020. 3. 28. 10:10
반응형

fs.readFile에서 데이터 가져 오기


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');
var content;
// First I want to read the file
fs.readFile('./Index.html', function read(err, data) {
    if (err) {
        throw err;
    }
    content = data;

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

function processFile() {
    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);
});

콜백에는 두 개의 인수 (err, data)가 전달되며 여기서 data는 파일의 내용입니다.

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


동기식

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와의 비동기 사용

mz모듈은 약속 된 버전의 코어 노드 라이브러리를 제공합니다. 그것들을 사용하는 것은 간단합니다. 먼저 라이브러리를 설치하십시오 ...

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

var data = fs.readFileSync('tmp/reltioconfig.json','utf8');

출력을 버퍼로 표시하는 인코딩없이 파일을 동 기적으로 호출 할 때 사용하십시오.


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

//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 에서 사용 가능 합니다.


말한 것처럼 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!");
      });
    });
  }

이 라인은 작동합니다

const content = fs.readFileSync('./Index.html', 'utf8');
console.log(content);

내장 된 Promisify 라이브러리 (노드 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);
  }
}

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

당신은 파일을 읽을 수 있습니다

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

이것은 비동기입니다. 익숙해지기 어려울 지 모르지만 그것이 바로 그것입니다. 다시 말하지만 이것은 비동기가 무엇인지에 대한 거칠지 만 빠른 설명입니다.


다음은 async랩 또는 약속 then체인에 작동하는 기능입니다.

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

참고 URL : https://stackoverflow.com/questions/10058814/get-data-from-fs-readfile

반응형