我在 Nuxt 2.15.4 上,store
如果文件按fs-extra
包存在于 nuxt 目录中,我想检查我的代码。
它在模块中很简单,因为我可以通过以下代码获取文件路径:
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
}