비동기/대기로 파일을 올바르게 읽는 방법은 무엇입니까?
어떻게 해야 할지 모르겠어요async/await효과가 있어요. 조금 이해는 되는데 잘 안 되네요.
function loadMonoCounter() {
fs.readFileSync("monolitic.txt", "binary", async function(err, data) {
return await new Buffer( data);
});
}
module.exports.read = function() {
console.log(loadMonoCounter());
};
알아요, 제가 좀readFileSync하지만 내가 그렇게 한다면, 난 절대 이해하지 못할 거라는 걸요.async/await그리고 그 문제는 그냥 묻어 두겠습니다.
목표: 통화loadMonoCounter()파일의 내용을 반환합니다.
해당 파일은 매번 증가합니다.incrementMonoCounter()(매 페이지 로드)라고 합니다.이 파일에는 버퍼의 덤프가 이진 형식으로 포함되어 있으며 SSD에 저장됩니다.
어떤 작업을 해도 오류가 발생하거나undefined콘솔에서
Node v11.0.0fs 약속은 기본적으로 사용 가능하므로promisify:
const fs = require('fs').promises;
async function loadMonoCounter() {
const data = await fs.readFile("monolitic.txt", "binary");
return Buffer.from(data);
}
사용하기await/async당신은 약속을 이행하는 방법이 필요합니다.핵심 API 함수는 다음과 같은 래퍼 없이는 이를 수행할 수 없습니다.
const fs = require('fs');
const util = require('util');
// Convert fs.readFile into Promise version of same
const readFile = util.promisify(fs.readFile);
function getStuff() {
return readFile('test');
}
// Can't use `await` outside of an async function so you need to chain
// with then()
getStuff().then(data => {
console.log(data);
})
참고로,readFileSync콜백을 받지 않고 데이터를 반환하거나 예외를 발생시킵니다.제공하는 기능이 무시되고 실제 반환 값을 캡처하지 못하기 때문에 원하는 값을 얻을 수 없습니다.
@Joel's 답변의 TypeScript 버전입니다.노드 11.0 이후에 사용할 수 있습니다.
import { promises as fs } from 'fs';
async function loadMonoCounter() {
const data = await fs.readFile('monolitic.txt', 'binary');
return Buffer.from(data);
}
사용할 수 있습니다.fs.promisesNode v11.0.0 이후 기본적으로 사용 가능
import fs from 'fs';
const readFile = async filePath => {
try {
const data = await fs.promises.readFile(filePath, 'utf8')
return data
}
catch(err) {
console.log(err)
}
}
다음과 같은 약속으로 readFile 명령을 쉽게 래핑할 수 있습니다.
async function readFile(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, 'utf8', function (err, data) {
if (err) {
reject(err);
}
resolve(data);
});
});
}
다음을 사용합니다.
await readFile("path/to/file");
노드 v14.0.0에서
const {readFile} = require('fs/promises');
const myFunction = async()=>{
const result = await readFile('monolitic.txt','binary')
console.log(result)
}
myFunction()
의 모든 기능을 유지 및 유지하기 위해fs:
const fs = require('fs');
const fsPromises = fs.promises;
async function loadMonoCounter() {
const data = await fsPromises.readFile('monolitic.txt', 'binary');
return new Buffer(data);
}
가져오는 중fs그리고.fs.promises별도로 전체에 대한 액세스 권한을 부여합니다.fsAPI를 보다 읽기 쉽게 유지하는 동시에...그래서 다음 예시와 같은 것이 쉽게 달성될 수 있습니다.
// the 'next example'
fsPromises.access('monolitic.txt', fs.constants.R_OK | fs.constants.W_OK)
.then(() => console.log('can access'))
.catch(() => console.error('cannot access'));
있습니다.fs.readFileSync( path, options )동기식 방법입니다.
const fs = require("fs");
const util = require("util");
const readFile = util.promisify(fs.readFile);
const getContent = async () => {
let my_content;
try {
const { toJSON } = await readFile("credentials.json");
my_content = toJSON();
console.log(my_content);
} catch (e) {
console.log("Error loading client secret file:", e);
}
};
를 사용하여 파일을 읽습니다.Promise나에게 적합한 것은:
const fs = require('fs')
//function which return Promise
const read = (path, type) => new Promise((resolve, reject) => {
fs.readFile(path, type, (err, file) => {
if (err) reject(err)
resolve(file)
})
})
//example how call this function
read('file.txt', 'utf8')
.then((file) => console.log('your file is '+file))
.catch((err) => console.log('error reading file '+err))
//another example how call function inside async
async function func() {
let file = await read('file.txt', 'utf8')
console.log('your file is '+file)
}
이렇게 하면 파일 내용에서 문자열이 생성됩니다. 이 작업을 위해 약속을 사용할 필요가 없습니다.
const fs = require('fs');
const data = fs.readFileSync("./path/to/file.json", "binary");
아래에서 제 접근 방식을 찾을 수 있습니다.먼저 fsasfsBase를 요구한 다음 fs 변수 안에 "약속"을 넣었습니다.
const fsBase = require('fs');
const fs = fsBase.promises
const fn = async () => {
const data = await fs.readFile('example.txt', 'utf8');
console.log(data);
};
fn();
이 예를 참조하십시오. https://www.geeksforgeeks.org/node-js-fs-readfile-method/
// Include fs module
var fs = require('fs');
// Use fs.readFile() method to read the file
fs.readFile('demo.txt', (err, data) => {
console.log(data);
})
언급URL : https://stackoverflow.com/questions/46867517/how-to-read-file-with-async-await-properly
'programing' 카테고리의 다른 글
| NOLOCK(Sql Server 힌트)는 나쁜 관행입니까? (0) | 2023.05.22 |
|---|---|
| Azure WebJob 시간 초과 구성 설정 (0) | 2023.05.22 |
| Mongoose 모델에서 메서드를 정의하려면 어떻게 해야 합니까? (0) | 2023.05.22 |
| 푸시되지 않은 기존 커밋 메시지를 수정하는 방법은 무엇입니까? (0) | 2023.05.22 |
| Is Nothing 대 Is Nothing (0) | 2023.05.22 |