programing

node.js의 파일 시스템을 비동기 / wait와 함께 사용하고 있습니다.

goodjava 2023. 1. 14. 09:30

node.js의 파일 시스템을 비동기 / wait와 함께 사용하고 있습니다.

파일 시스템 조작에 비동기/대기 기능을 사용하고 싶습니다.비동기/대기 기능은 정상적으로 동작합니다.babel-plugin-syntax-async-functions.

하지만 이 코드로 인해 나는 만약의 경우에 직면하게 된다names정의되어 있지 않습니다.

import fs from 'fs';

async function myF() {
  let names;
  try {
    names = await fs.readdir('path/to/dir');
  } catch (e) {
    console.log('e', e);
  }
  if (names === undefined) {
    console.log('undefined');
  } else {
    console.log('First Name', names[0]);
  }
}

myF();

코드를 콜백헬 버전으로 리빌드하면 모든 것이 정상이며 파일명이 표시됩니다.조언해 주셔서 감사합니다.

비동기 네이티브 지원은 노드 11 이후 fs 기능을 대기하고 있습니다.

노드 이후JS 11.0.0(안정적) 및 버전 10.0.0(실험적)에서는 이미 promisify'd가 되어 있는 파일 시스템 메서드에 액세스 할 수 있습니다.try catch콜백의 반환된 값에 오류가 포함되어 있는지 확인하는 대신 예외 처리를 수행합니다.

API는 매우 깔끔하고 우아합니다!간단하게 사용.promises멤버fs오브젝트:

import fs from 'fs';
const fsPromises = fs.promises;

async function listDir() {
  try {
    return await fsPromises.readdir('path/to/dir');
  } catch (err) {
    console.error('Error occured while reading directory!', err);
  }
}

listDir();

노드 8.0.0부터는 다음을 사용할 수 있습니다.

const fs = require('fs');
const util = require('util');

const readdir = util.promisify(fs.readdir);

async function myF() {
  let names;
  try {
    names = await readdir('path/to/dir');
  } catch (err) {
    console.log(err);
  }
  if (names === undefined) {
    console.log('undefined');
  } else {
    console.log('First Name', names[0]);
  }
}

myF();

https://nodejs.org/dist/latest-v8.x/docs/api/util.html#util_util_promisify_original 를 참조해 주세요.

Node.js 8.0.0

네이티브 비동기 / 대기

프로미스화

이 버전부터는 util 라이브러리에서 네이티브 Node.js 함수를 사용할 수 있습니다.

const fs = require('fs')
const { promisify } = require('util')

const readFileAsync = promisify(fs.readFile)
const writeFileAsync = promisify(fs.writeFile)

const run = async () => {
  const res = await readFileAsync('./data.json')
  console.log(res)
}

run()


약속 포장

const fs = require('fs')

const readFile = (path, opts = 'utf8') =>
  new Promise((resolve, reject) => {
    fs.readFile(path, opts, (err, data) => {
      if (err) reject(err)
      else resolve(data)
    })
  })

const writeFile = (path, data, opts = 'utf8') =>
  new Promise((resolve, reject) => {
    fs.writeFile(path, data, opts, (err) => {
      if (err) reject(err)
      else resolve()
    })
  })

module.exports = {
  readFile,
  writeFile
}

...


// in some file, with imported functions above
// in async block
const run = async () => {
  const res = await readFile('./data.json')
  console.log(res)
}

run()

조언

항상 사용try..catch예외 상한을 재투입하지 않으려면 wait blocks를 선택합니다.

v10.0 이후로는

사용 예

const { promises: fs } = require("fs");

async function myF() {
    let names;
    try {
        names = await fs.readdir("path/to/dir");
    } catch (e) {
        console.log("e", e);
    }
    if (names === undefined) {
        console.log("undefined");
    } else {
        console.log("First Name", names[0]);
    }
}

myF();

사용 예

const { promises: fs } = require("fs");

async function getContent(filePath, encoding = "utf-8") {
    if (!filePath) {
        throw new Error("filePath required");
    }

    return fs.readFile(filePath, { encoding });
}

(async () => {
    const content = await getContent("./package.json");

    console.log(content);
})();

File-Api가 잘못된 동작을 일으킬 수 있습니다.fs.readdir는 약속을 반환하지 않습니다.콜백만 받습니다.async-ait 구문을 사용하는 경우 다음과 같이 함수를 '약속'할 수 있습니다.

function readdirAsync(path) {
  return new Promise(function (resolve, reject) {
    fs.readdir(path, function (error, result) {
      if (error) {
        reject(error);
      } else {
        resolve(result);
      }
    });
  });
}

대신 이렇게 부르세요.

names = await readdirAsync('path/to/dir');

질문에 대한 TypeScript 버전입니다.노드 11.0 이후에 사용할 수 있습니다.

import { promises as fs } from 'fs';

async function loadMonoCounter() {
    const data = await fs.readFile('monolitic.txt', 'binary');
    return Buffer.from(data);
}

노드 v14.0.0 이후

다음 작업을 수행할 수 있습니다.

import { readdir } from "fs/promises";

로부터 수입할 수 있는"fs"

상세한 것에 대하여는, 다음의 PR 를 참조해 주세요.https://github.com/nodejs/node/pull/31553

프로미스 버전을 내보내는 작은 도움말모듈이 있습니다.fs기능들

const fs = require("fs");
const {promisify} = require("util")

module.exports = {
  readdir: promisify(fs.readdir),
  readFile: promisify(fs.readFile),
  writeFile: promisify(fs.writeFile)
  // etc...
};

다음과 같은 이점이 있습니다.

const fsp = require('fs-promise');

(async () => {
  try {
    const names = await fsp.readdir('path/to/dir');
    console.log(names[0]);
  } catch (e) {
    console.log('error: ', e);
  }
})();

코드는, 하모니 플래그가 유효하게 되어 있는 경우, 바벨이 없는 노드 7.6으로 동작합니다.node --harmony my-script.js노드 7.7부터는 이 플래그가 필요 없습니다.

첫머리에 포함된 라이브러리는 의 프로미스화된 래퍼에 불과합니다.fs(및 ).

요즘은 babel 없이 노드에서 무엇을 할 수 있는지 정말 기대됩니다!네이티브async/await코드를 쓰는 것을 매우 즐겁게 해 주세요!

업데이트 2017-06: fs-promise 모듈이 더 이상 사용되지 않습니다.대신 동일한 API를 사용합니다.

커스텀 기능과 비교하여 https://github.com/davetemplin/async-file, 등의 npm 패키지를 사용할 것을 권장합니다.예를 들어 다음과 같습니다.

import * as fs from 'async-file';

await fs.rename('/tmp/hello', '/tmp/world');
await fs.appendFile('message.txt', 'data to append');
await fs.access('/etc/passd', fs.constants.R_OK | fs.constants.W_OK);

var stats = await fs.stat('/tmp/hello', '/tmp/world');

다른 답변은 구식입니다.

비동기 방식과 동기 방식을 모두 지원하는 심플하고 가벼운 모듈 https://github.com/nacholibre/nwc-l 를 사용할 수 있습니다.

주의: 이 모듈은 제가 만들었습니다.

언급URL : https://stackoverflow.com/questions/40593875/using-filesystem-in-node-js-with-async-await