question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

EPERM: operation not permitted, mkdir

See original GitHub issue

First, I’m sorry my English is very bad.

I call copySync in the main thread can work fine, but when the asynchronous call it is report error (post => /sync). In addition, I use ensureDirSync to create a directory that does not exist right, it’s work fine.

Looks like it can only write a file can not write a directory

The code is large, find the keywords ‘svfs.copy’ and ‘nuxtBuild’ please.

My main code is here: server/fs.js

import fs from 'fs'
import fsextra from 'fs-extra'

export default {
  /**
   * 创建目录,如果不存在
   * @param {string} dir
   */
  mkdir(dir) {
    if (dir == null) {
      return
    }
    fsextra.ensureDirSync(dir)
  },
  /**
   * 复制文件
   * @param {string} src
   * @param {string} dest
   */
  copy(src, dest) {
    if (src == null || dest == null) {
      return
    }
    console.log(`copy from ${src} to ${dest}`)
    fsextra.copySync(src, dest)
  },
  /**
   * 清空目录/删除目录下所有
   * @param {string} dir
   */
  emptyDir(dir) {
    if (dir == null) {
      return
    }
    this.removeFileFromDir(dir, file => {
      return file.toLowerCase() !== '.gitkeep'
    })
  },
  /**
   * 删除目录下部分文件/目录
   * @param {string} dir
   * @param {function} fn
   */
  removeFileFromDir(dir, fn) {
    if (dir == null) {
      return
    }
    fn = typeof fn === 'function' ? fn : file => {
      return true
    }
    fs.readdirSync(dir).forEach(file => {
      if (fn(file)) {
        this.removeFile(`${dir}/${file}`)
      }
    })
  },
  /**
   * 删除文件/目录
   * @param {string} file
   */
  removeFile(file) {
    if (file) {
      console.log('del', file)
      fsextra.removeSync(file)
    }
  }
}

server/index.js

import path from 'path'
import Koa from 'koa'
import KoaRouter from 'koa-router'
import Boom from 'boom'
import bodyParser from 'koa-bodyparser'
import c2k from 'koa2-connect'
import proxy from 'http-proxy-middleware'
import { Nuxt, Builder } from 'nuxt'
import svfs from './fs'

const app = new Koa()
const router = new KoaRouter()
const host = process.env.HOST || '127.0.0.1'
const port = process.env.PORT || 9086

// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
config.dev = !(app.env === 'production')

// config.build.buildDir 不配置默认.nuxt
// fsextra.removeSync(/^\.nuxt/) // fsextra.removeSync 不支持正则
svfs.removeFileFromDir('./', file => {
  return file.toLowerCase().startsWith('.nuxt')
})

// 是否正在构建
const Separator = '-'
// let isBuilding = false
let buildIndex = 0
let nuxt
// Instantiate nuxt.js
function nuxtBuild() {
  // isBuilding = true
  if (nuxt) {
    config.build.buildDir = `${nuxt.options.buildDir.split(Separator)[0]}-${++buildIndex}` // 换一个目录
  }
  const innerNuxt = new Nuxt(config) // 如果重复利用Nuxt, nuxt在build的时候是不能提供服务的, 所以每次new
  if (nuxt == null) { // 初始化的时候第一次没有,直接赋值
    nuxt = innerNuxt
  }

  const pagePath = path.join(__dirname, '../pages') // nuxt的pages页面目录
  svfs.emptyDir(pagePath) // 清空
  try {
    // EPERM: operation not permitted, mkdir: When the asynchronous 'sync' calls it
    svfs.copy(config.skin.getPagesPath.apply(innerNuxt), pagePath) // 复制新的 
  } catch (e) {
    console.error(123)
    console.error(e)
    svfs.mkdir(Date.now().toString()) // work fine
  }

  const builder = new Builder(innerNuxt)
  builder.build().then(() => {
    if (nuxt === innerNuxt) {
    } else {
      const temp = nuxt
      nuxt = innerNuxt
      temp.close()
    }
    // isBuilding = false
    console.log('Build completed!')
  }).catch(e => {
    console.error(e)
    process.exit(1)
  })
}

// Build in development
const doAPIReg = /\.do$/
const cp = c2k(proxy({
  target: 'http://localhost:8082/portal/'
}))

if (config.dev) {
  router.get(doAPIReg, cp)

  router.post(doAPIReg, cp)

  nuxtBuild()
}

app.use(bodyParser())

app.use(router.routes())
app.use(router.allowedMethods({
  throw: true,
  /* eslint-disable new-cap */
  notImplemented: () => new Boom.notImplemented(),
  methodNotAllowed: () => new Boom.methodNotAllowed()
}))

router.post('/sync', (ctx, next) => {
  console.log('收到同步请求 ---> ', ctx.request.body)
  ctx.status = 200
  ctx.response.body = {
    result: 123
  }

  nuxtBuild.apply(this)
})

router.get(/(^\/_nuxt(?:\/|$))|(^\/(?:__webpack_hmr|$)$)/, async function(ctx, next) {
  ctx.status = 200 // koa defaults to 404 when it sees that status is unset

  await new Promise((resolve, reject) => {
    ctx.res.on('close', resolve)
    ctx.res.on('finish', resolve)
    nuxt.render(ctx.req, ctx.res, promise => {
      // nuxt.render passes a rejected promise into callback on error.
      promise.then(resolve).catch(reject)
    })
  })
})

app.listen(port, host)
console.log(`Server listening on ${host}:${port}`)

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:11 (1 by maintainers)

github_iconTop GitHub Comments

2reactions
jprichardsoncommented, Sep 9, 2017

@yoyo837 you’re going to need you to distill this down into a small and minimal reproducible test case. We’re not going to debug your entire code.

0reactions
yoyo837commented, Sep 10, 2017

I think I might know what the problem is: I empty it and copy the target directory from another is also being watched to modify the file.

Thanks for your reply. @RyanZim and @jprichardson 😃

Read more comments on GitHub >

github_iconTop Results From Across the Web

npm - EPERM: operation not permitted on Windows
My Solution for the problem · Right-click on the project folder · Go to properties -> Security Tab · Select Users -> Edit...
Read more >
Error: EPERM: operation not permitted, mkdir 'C ... - GitHub
I was facing the same problem for 3 days and got this solution for it... It's because of old files lying in your...
Read more >
Error: EPERM: operation not permit… | Apple Developer Forums
I am installing packages for NODEJS/NPM and am receiving the following error, which, apparently, is not an error with the software, but with...
Read more >
Solution to npm install "npm ERR! Error: EPERM - webfoobar
Error: EPERM: operation not permitted" error. I was trying to install pngquant imagemin plugin using this command: npm install imagemin-pngquant.
Read more >
sfdx update fails, Error: EPERM: operation not permitted
I went to the location specified in the error. · Copied the location. · Search for environment variables in windows search bar ·...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found