簡體   English   中英

如何檢查nuxt中是否存在文件

[英]How to check if a file exist in nuxt

我在 Nuxt 2.15.4 上,如果fs-extra package 在 nuxt 目錄中存在文件,我想檢查我的store代碼。

它在模塊中很簡單,因為我可以通過以下代碼獲取文件路徑:

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

#更新

即使使用if(fse.pathExistsSync('./static/myfile.json'))語句,如果文件不存在, require('../assets/mainfile.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)
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM