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

问题描述

我在 Nuxt 2.15.4 上,如果 store 包在 nuxt 目录中存在文件,我想检查我的 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',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',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,mainfile)
  }