source

파일이 nuxt에 있는지 확인하는 방법

goodcode 2022. 8. 20. 19:00
반응형

파일이 nuxt에 있는지 확인하는 방법

나는 Nuxt 2.15.4에 있고 나는 나의 체크인을 하고 싶다.storenuxt 디렉토리에 파일이 존재하는 경우 코드 지정:fs-extra패키지.

이 코드로 파일 경로를 얻을 수 있기 때문에 모듈에서는 간단합니다.

const path = require('path')
const fse = require('fs-extra');
const FilePath = path.join(this.options.rootDir, './static/myfile.json')
const fse = require('fs-extra');
fse.pathExists(FilePath, (err, exists) => {
    console.log(err) // => null
    console.log(exists) // => true
})

하지만vuex store에 액세스 할 수 없습니다.this.options.rootDir이 코드는 항상 false를 반환합니다.

export const actions = {
  async nuxtServerInit({dispatch, commit}) {
    if(process.server){
      const fse = require('fs-extra');
      fse.pathExists('~/static/myfile.json', (err, exists) => {
        console.log(err) // => null
        console.log(exists) // => false
      })
    }
  }
}

파일을 풀패스로 가져오거나 종료 여부를 확인하려면 어떻게 해야 합니까?

#업데이트

내 파일 경로에 작은 실수가 있었던 것 같습니다../static/myfile.json확인 완료!!

다른 문제가 생겼어!!다른 json 파일이 있는데Object.assign(mainfile, myfile)안 돼!!

다음은 샘플입니다.

  async nuxtServerInit({dispatch, commit}) {
    let mainfile = require('../assets/mainfile.json')
    // if i use assign here it works and merge them together
    // let myfile = require('../assets/myfile.json')
    // Object.assign(mainfile, myfile)
    if(process.server){
      const fse = require('fs-extra');
      fse.pathExists('./static/myfile.json', (err, exists) => {
        if(exists){
          Object.assign(mainfile, myfile)
          commit('SET_FILE', mainfile); // this send the unmerged file to mutation
          console.log(mainfile); // but get the merged json here
        }
      })
      console.log(mainfile); // it is unmerged
    }
    console.log(mainfile); // it is unmerged
  }

갱신된 질문에 대해서는 다음 사항을 확인해 주십시오.exists루프로 들어가는 게 너무 진부하고mainfile예상한 형식으로 되어 있습니다.
그러면 할 수 있어요.

mainfile = {...mainfile, ...myfile} // rather than Object.assign

네, @kissu 덕분에 문제가 발견되었습니다.Kissu가 댓글에서 언급했듯이commit동기화되어 있습니다.액션을 기다리려고 했지만 결과를 얻지 못했기 때문에pathExistsSync대신 끝!!

  async nuxtServerInit({dispatch, commit}) {
    let myfile = {}
    let mainfile = require('../assets/mainfile.json')
    if(process.server){
      const fse = require('fs-extra');
      if(fse.pathExistsSync('./static/myfile.json')){
          myfile = require('../assets/myfile.json')
          Object.assign(mainfile, myfile)
      }
    }
    await dispatch('setMyFile', mainfile)
  }

#업데이트

require('../assets/mainfile.json')파일이 존재하지 않는 경우에도 오류가 발생합니다.if(fse.pathExistsSync('./static/myfile.json'))스테이트먼트:

  async nuxtServerInit({dispatch, commit}) {
    let myfile = {}
    let mainfile = require('../assets/mainfile.json')
    if(process.server){
      const fse = require('fs-extra');
      if(fse.pathExistsSync('./static/myfile.json')){
          myfile = readJsonSync('./static/myfile.json')
          Object.assign(mainfile, myfile)
      }
    }
    await dispatch('setMyFile', mainfile)
  }

언급URL : https://stackoverflow.com/questions/67357894/how-to-check-if-a-file-exist-in-nuxt

반응형