텍스트 파일의 파일 이름 목록을 js 배열로로드하려고합니다.
이 작업을 수행하기 위해 fs 모듈을 사용하려고 시도했으며 readFile 함수 내에서 배열을 성공적으로 인쇄 할 수 있지만 배열을 반환하고 외부에서 인쇄하려고하면 그렇게 할 수 없습니다.
const fs = require("fs");
function parseFileList(fileToRead){
fs.readFile(fileToRead, 'utf8', (err, data) => {
if (err) throw err;
const textByLine = data.split("\n").slice(0,-1);
return textByLine;
});
}
const refList = parseFileList(argv.ref);
console.log(refList);
파일의 파일 이름은 문자열 배열로 출력되어야합니다. 하지만 지금은 그냥 인쇄 undefined
됩니다. 나는 이것이 readFile이 비동기라는 사실과 관련이 있다고 생각하지만 그것을 해결하는 방법을 모르겠습니다.
콜백에서 응답을 받기 때문입니다. 이 함수를 작동 시키려면 Promise로 변환해야합니다.
function parseFileList(fileToRead){
return new Promise((resolve, reject) => {
fs.readFile(fileToRead, 'utf8', (err, data) => {
if (err) reject(err);
const textByLine = data.split("\n").slice(0,-1);
return resolve(textByLine);
});
})
}
이제 다음과 같이 사용할 수 있습니다.
parseFileList(filename).then(data => console.log(data))
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다