fs-extra#mkdirp TypeScript Examples

The following examples show how to use fs-extra#mkdirp. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: generate-packages.ts    From DefinitelyTyped-tools with MIT License 6 votes vote down vote up
export default async function generatePackages(
  dt: FS,
  allPackages: AllPackages,
  changedPackages: ChangedPackages,
  tgz = false
): Promise<void> {
  const [log, logResult] = logger();
  log("\n## Generating packages");

  await mkdirp(outputDirPath);
  await emptyDir(outputDirPath);

  for (const { pkg, version } of changedPackages.changedTypings) {
    await generateTypingPackage(pkg, allPackages, version, dt);
    if (tgz) {
      await writeTgz(outputDirectory(pkg), `${outputDirectory(pkg)}.tgz`);
    }
    log(` * ${pkg.desc}`);
  }
  log("## Generating deprecated packages");
  await withNpmCache(
    new UncachedNpmInfoClient(),
    async (client) => {
      for (const pkg of changedPackages.changedNotNeededPackages) {
        log(` * ${pkg.libraryName}`);
        await generateNotNeededPackage(pkg, client, log);
      }
    },
    cacheDirPath
  );
  await writeLog("package-generator.md", logResult());
}
Example #2
Source File: deleteDuplicateNote.test.ts    From joplin-utils with MIT License 6 votes vote down vote up
describe('删除重复的笔记', () => {
  const tempPath = path.resolve(__dirname, '.temp/exportDuplicationNoteList')
  beforeEach(async () => {
    await remove(tempPath)
    await mkdirp(tempPath)
  })
  it('加载所有重复的笔记', async () => {
    const noteList = await PageUtil.pageToAllList(noteApi.list, {
      fields: ['id', 'title', 'user_updated_time', 'body'],
    })
    const map = groupBy(noteList, (note) => note.title)
    const deleteNoteList = Object.entries(map)
      .filter(([_, notes]) => notes.length > 1)
      .map(
        ([_, notes]) =>
          sortBy(
            notes as Pick<
              NoteProperties,
              'user_updated_time' | 'title' | 'body' | 'id'
            >[],
            (note) => note.user_updated_time,
          )[0],
      )
    await mkdirp(tempPath)
    for (let note of deleteNoteList) {
      const filePath = path.resolve(tempPath, note.title.trim() + '.md')
      try {
        await writeFile(filePath, note.body, {
          encoding: 'utf-8',
        })
        await noteApi.remove(note.id)
      } catch (e) {
        console.log('删除失败: ', note.title)
      }
    }
  })
})
Example #3
Source File: ResourceWriter.ts    From joplin-blog with MIT License 6 votes vote down vote up
async clean() {
    const postPath = path.resolve(this.config.postPath)
    const resourcePath = path.resolve(this.config.resourcePath)

    async function clean(dirPath: string) {
      if (await pathExists(dirPath)) {
        await remove(dirPath)
      }
      await mkdirp(dirPath)
    }

    await Promise.all([clean(postPath), clean(resourcePath)])
  }
Example #4
Source File: WikiVuepressIntegrated.ts    From joplin-blog with MIT License 6 votes vote down vote up
async init() {
    await this.resourceWriter.clean()
    const sidebarConfigPath = path.resolve(
      this.config.rootPath,
      '.vuepress/sidebar.json',
    )
    await mkdirp(path.resolve(this.config.rootPath, 'p/resource'))
    await mkdirp(path.dirname(sidebarConfigPath))
    await writeJson(sidebarConfigPath, await this.buildSidebar(), {
      spaces: 2,
    })
  }
Example #5
Source File: createEmptyFile.test.ts    From joplin-utils with MIT License 6 votes vote down vote up
describe('测试 createEmptyFile', () => {
  const tempPath = path.resolve(__dirname, '.temp')
  beforeEach(async () => {
    await remove(tempPath)
    await mkdirp(tempPath)
  })
  it.skip('基本示例', async () => {
    const filePath = path.resolve(tempPath, 'test.drawio.svg')
    let handle: number
    try {
      handle = await createEmptyFile(filePath)
      expect(await readFile(filePath, 'utf-8')).toBe('')
    } finally {
      await close(handle!)
    }
  })
})
Example #6
Source File: BlogJekyllIntegrated.test.ts    From joplin-utils with MIT License 6 votes vote down vote up
describe('测试 BlogJekyllIntegrated', () => {
  const rootPath = path.resolve(__dirname, 'temp/jekyll-example')
  beforeEach(async () => {
    await remove(rootPath)
    await mkdirp(rootPath)
    await cacheCommanderProgram.init()
  })
  it('基本示例', async () => {
    const application = new Application(
      {
        token: config.token,
        baseUrl: config.baseUrl,
        tag: 'blog',
      },
      new BlogJekyllIntegrated({
        tag: 'blog',
        rootPath: rootPath,
      }),
    )

    const generatorEvents = new GeneratorEventsImpl()
    await application
      .gen()
      .on('readNoteAttachmentsAndTags', generatorEvents.readNoteAttachmentsAndTags)
      .on('parseAndWriteNotes', generatorEvents.parseAndWriteNotes)
      .on('writeNote', generatorEvents.writeNote)
      .on('copyResources', generatorEvents.copyResources)
  })
})
Example #7
Source File: JoplinNoteHandler.test.ts    From joplin-utils with MIT License 6 votes vote down vote up
describe('测试 JoplinNoteHandler', () => {
  const tempPath = path.resolve(__dirname, '.temp')
  beforeEach(async () => {
    await remove(tempPath)
    await mkdirp(tempPath)
  })
  it('基本示例', async () => {
    const text = `# test

1. one
2. two
`
    const md = JoplinNoteHandler.md
    expect(md.stringify(md.parse(text))).toBe(text)
  })
})
Example #8
Source File: Exporter.ts    From joplin-utils with MIT License 6 votes vote down vote up
async export() {
    await mkdirp(this.config.rootPath)
    console.log('读取目录')
    const folderList = await this.listFolder()
    await this.writeFolder(folderList)
    console.log('读取笔记')
    const noteList = await this.listNote(folderList)
    await this.writeNote(noteList)
    console.log('读取资源')
    const resourceList = await this.listResource()
    await this.writeResource(resourceList)
    console.log('读取标签')
    const { tagList, noteTagRelationList } = await this.tag()
    console.log('写入配置')
    await this.writeConfig({
      folderList,
      noteList: noteList.map(({ body, ...item }) => item) as any,
      resourceList,
      tagList,
      noteTagRelationList,
    })
  }
Example #9
Source File: Exporter.ts    From joplin-utils with MIT License 6 votes vote down vote up
async writeResource(list: ExportResource[]) {
    await mkdirp(path.resolve(this.config.rootPath, 'resources'))
    await AsyncArray.forEach(list, async (item) => {
      await writeFile(
        path.resolve(this.config.rootPath, 'resources', item.fileTitle),
        await resourceApi.fileByResourceId(item.id),
      )
    })
  }
Example #10
Source File: Exporter.ts    From joplin-utils with MIT License 6 votes vote down vote up
async writeConfig(config: ExportConfig) {
    const configPath = path.resolve(this.config.rootPath, 'config')
    await mkdirp(configPath)
    await AsyncArray.forEach(Object.entries(config), async ([fileName, v]) => {
      await writeJson(path.resolve(configPath, fileName + '.json'), v, {
        spaces: 2,
      })
    })
  }
Example #11
Source File: Exporter.test.ts    From joplin-utils with MIT License 6 votes vote down vote up
describe('测试 Export', () => {
  const exporter = new Exporter({
    rootPath: path.resolve(__dirname, '.temp'),
  })
  beforeAll(async () => {
    setupJoplinConfig()
    await remove(exporter.config.rootPath)
    await mkdirp(exporter.config.rootPath)
  })
  it('测试 folder', async () => {
    const folderList = await exporter.listFolder()
    console.log('folderList: ', folderList)
    await exporter.writeFolder(folderList)
  })
  it('测试 notes', async () => {
    const folderList = await exporter.listFolder()
    const noteList = await exporter.listNote(folderList)
    console.log(
      'noteList: ',
      noteList.map((item) => item.filePath),
    )
    await exporter.writeNote(noteList)
  })
  it('测试 resource', async () => {
    const resourceList = await exporter.listResource()
    console.log('resourceList: ', resourceList)
    await exporter.writeResource(resourceList)
  })

  it('测试 tag', async () => {
    const { tagList, noteTagRelationList } = await exporter.tag()
    console.log('tagList: ', tagList, noteTagRelationList)
  })

  it('测试 export', async () => {
    await exporter.export()
  })
})
Example #12
Source File: generate-packages.ts    From DefinitelyTyped-tools with MIT License 5 votes vote down vote up
async function outputFilePath(pkg: AnyPackage, filename: string): Promise<string> {
  const full = joinPaths(outputDirectory(pkg), filename);
  const dir = path.dirname(full);
  if (dir !== outputDirectory(pkg)) {
    await mkdirp(dir);
  }
  return full;
}
Example #13
Source File: TagUseService.ts    From joplin-utils with MIT License 5 votes vote down vote up
private async init() {
    if (!(await pathExists(this.configPath))) {
      await mkdirp(path.dirname(this.configPath))
      await writeJson(this.configPath, {
        tagUse: [],
      })
    }
  }
Example #14
Source File: JoplinNoteCommandService.ts    From joplin-utils with MIT License 5 votes vote down vote up
async init(appConfig: AppConfig) {
    if (!appConfig.token) {
      return
    }
    config.token = appConfig.token
    config.baseUrl = appConfig.baseUrl

    setInterval(async () => {
      await this.config.noteViewProvider.refresh()
    }, 1000 * 10)
    const tempNoteDirPath = path.resolve(GlobalContext.context.globalStorageUri.fsPath, '.tempNote')
    const tempResourceDirPath = path.resolve(GlobalContext.context.globalStorageUri.fsPath, '.tempResource')
    await AsyncArray.forEach([tempNoteDirPath, tempResourceDirPath], async (path) => {
      // await remove(path)
      await mkdirp(path)
    })
    watch(tempNoteDirPath)
      .on('change', async (filePath) => {
        const id = GlobalContext.openNoteMap.get(filePath)
        if (!id) {
          return
        }
        const content = await readFile(filePath, 'utf-8')
        const { title, body } = JoplinNoteUtil.splitTitleBody(content)
        const newNote = { id, body } as NoteProperties
        if (title) {
          newNote.title = title.startsWith('# ') ? title.substring(2) : title
        }
        await noteApi.update(newNote)
        this.config.noteViewProvider.fire()
        const resourceList = await noteApi.resourcesById(id)
        GlobalContext.openNoteResourceMap.set(id, resourceList)
      })
      .on('error', (err) => {
        logger.error('watch note error', err)
      })
    watch(tempResourceDirPath)
      .on('change', async (filePath) => {
        const id = GlobalContext.openResourceMap.get(filePath)
        if (!id) {
          return
        }
        await resourceApi.update({
          id,
          // title: path.basename(filePath),
          data: createReadStream(filePath),
        })
      })
      .on('error', (err) => {
        logger.error('watch resource error', err)
      })
  }
Example #15
Source File: Exporter.ts    From joplin-utils with MIT License 5 votes vote down vote up
async writeFolder(folderList: ExportFolder[]) {
    await AsyncArray.map(folderList, async (item) => {
      await mkdirp(path.resolve(this.config.rootPath, 'notes', item.filePath))
    })
  }
Example #16
Source File: WikiVuepressIntegrated.ts    From joplin-utils with MIT License 5 votes vote down vote up
async init() {
    const sidebarConfigPath = path.resolve(this.config.rootPath, '.vuepress/sidebar.json')
    await mkdirp(path.dirname(sidebarConfigPath))
    await writeJson(sidebarConfigPath, await this.buildSidebar(), {
      spaces: 2,
    })
  }
Example #17
Source File: Application.ts    From joplin-utils with MIT License 5 votes vote down vote up
/**
   * 初始化资源目录
   */
  async initDir() {
    await Promise.all([mkdirp(this.handler.notePath), mkdirp(this.handler.resourcePath)])
  }
Example #18
Source File: BlogVuepressIntegrated.ts    From joplin-blog with MIT License 5 votes vote down vote up
async init() {
    await this.resourceWriter.clean()
    await mkdirp(path.resolve(this.config.rootPath, '_posts/resource'))
  }
Example #19
Source File: extension.ts    From joplin-utils with MIT License 4 votes vote down vote up
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
// noinspection JSUnusedLocalSymbols
export async function activate(context: vscode.ExtensionContext) {
  GlobalContext.context = context
  appConfig.loadConfig()
  console.log('logPath: ', context.logUri.fsPath)
  await mkdirp(context.logUri.fsPath)
  logger
    .add(new transports.File({ filename: path.resolve(context.logUri.fsPath, 'error.log'), level: 'error' }))
    .add(new transports.File({ filename: path.resolve(context.logUri.fsPath, 'combined.log') }))
  await init()
  if (!(await checkJoplinServer())) {
    return
  }
  const noteExplorerProvider = new NoteExplorerProvider()
  const noteListTreeView = vscode.window.createTreeView('joplin-note', {
    treeDataProvider: noteExplorerProvider,
  })
  const joplinNoteCommandService = ClassUtil.bindMethodThis(
    new JoplinNoteCommandService({
      noteViewProvider: noteExplorerProvider,
      noteListTreeView,
    }),
  )
  await joplinNoteCommandService.init(appConfig)
  const handlerService = ClassUtil.bindMethodThis(new HandlerService(joplinNoteCommandService))
  GlobalContext.handlerService = handlerService
  joplinNoteCommandService.handlerService = handlerService

  //region register commands

  registerCommand('joplinNote.refreshNoteList', noteExplorerProvider.refresh.bind(noteExplorerProvider))
  registerCommand('joplinNote.search', joplinNoteCommandService.search)
  registerCommand('joplinNote.openNote', joplinNoteCommandService.openNote)

  registerCommand('joplinNote.createFolder', (item) => joplinNoteCommandService.create(TypeEnum.Folder, item))
  registerCommand('joplinNote.createNote', (item) => joplinNoteCommandService.create(TypeEnum.Note, item))
  registerCommand('joplinNote.rename', joplinNoteCommandService.rename)
  registerCommand('joplinNote.copyLink', joplinNoteCommandService.copyLink)
  registerCommand('joplinNote.remove', joplinNoteCommandService.remove)
  registerCommand('joplinNote.cut', joplinNoteCommandService.cut)
  registerCommand('joplinNote.paste', joplinNoteCommandService.paste)
  registerCommand('joplinNote.toggleTodoState', joplinNoteCommandService.toggleTodoState)
  registerCommand('joplinNote.createResource', joplinNoteCommandService.createResource)
  registerCommand('joplinNote.removeResource', joplinNoteCommandService.removeResource)
  registerCommand('joplinNote.manageTags', joplinNoteCommandService.manageTags)
  registerCommand('joplinNote.createTag', joplinNoteCommandService.createTag)
  registerCommand('joplinNote.removeTag', joplinNoteCommandService.removeTag)
  registerCommand('joplinNote.showCurrentlyOpenNote', async () => {
    {
      const activeFileName = vscode.window.activeTextEditor?.document.fileName
      if (!activeFileName) {
        return
      }
      await joplinNoteCommandService.onDidChangeActiveTextEditor(activeFileName)
    }
  })
  registerCommand('joplinNote.showLogFileDir', () => vscode.env.openExternal(context.logUri))
  vscode.window.onDidChangeActiveTextEditor((e) =>
    joplinNoteCommandService.onDidChangeActiveTextEditor(e?.document.fileName),
  )

  //endregion

  //region register image upload

  registerCommand(
    'joplinNote.uploadImageFromClipboard',
    uploadResourceService.uploadImageFromClipboard.bind(uploadResourceService),
  )
  registerCommand(
    'joplinNote.uploadImageFromExplorer',
    uploadResourceService.uploadImageFromExplorer.bind(uploadResourceService),
  )
  registerCommand(
    'joplinNote.uploadFileFromExplorer',
    uploadResourceService.uploadFileFromExplorer.bind(uploadResourceService),
  )

  //endregion

  //region register other service

  vscode.workspace.onDidCloseTextDocument(handlerService.handleCloseTextDocument)
  vscode.window.registerUriHandler({
    handleUri: handlerService.uriHandler,
  })
  const docFilter: vscode.DocumentSelector = {
    language: 'markdown',
    scheme: 'file',
    pattern: '**/rxliuli.joplin-vscode-plugin/.tempNote/*.md',
  }
  const linkProvider = new JoplinMarkdownLinkProvider()
  context.subscriptions.push(
    vscode.languages.registerDocumentLinkProvider(docFilter, linkProvider),
    vscode.languages.registerHoverProvider(docFilter, linkProvider),
  )

  //endregion

  //region register markdown support

  return {
    extendMarkdownIt(md: MarkdownIt) {
      return md.use(useJoplinLink(GlobalContext.openNoteResourceMap)).use(
        useJoplinImage({
          token: appConfig.token!,
          baseUrl: appConfig.baseUrl!,
        }),
      )
    },
  }

  //endregion
}
Example #20
Source File: ResourceApi.test.ts    From joplin-utils with MIT License 4 votes vote down vote up
describe('test ResourceApi', () => {
  let id: string
  beforeAll(async () => {
    id = (await createTestResource()).id
  })
  afterAll(async () => {
    await resourceApi.remove(id)
  })
  const tempPath = path.resolve(__dirname, '.temp')
  beforeEach(async () => {
    await remove(tempPath)
    await mkdirp(tempPath)
  })
  it('test list', async () => {
    const res = await resourceApi.list({ fields: ['id', 'title'] })
    console.log(res)
    expect(res.items.length).toBeGreaterThan(0)
  })
  it('test get', async () => {
    const res = await resourceApi.get(id)
    console.log(res)
    expect(res.id).toBe(id)
  })
  /**
   * TODO 一个官方未修复的 bug,参考:https://github.com/laurent22/joplin/issues/4575
   */
  it.skip('test get filename', async () => {
    const res = await resourceApi.get(id, ['id', 'filename'])
    console.log(res)
    expect(res.filename).not.toBe('')
  })

  describe('diff fetch and axios', () => {
    const path = resolve(__dirname, '../resource/resourcesByFileId.png')
    it('test create', async () => {
      const title = 'image title'
      const json = await resourceApi.create({
        title,
        data: createReadStream(path),
      })
      expect(json.title).toBe(title)
    })
  })
  describe('test update', () => {
    it('basic example', async () => {
      const title = `new title ${Date.now()}`
      const updateRes = await resourceApi.update({ id, title })
      expect(updateRes.title).toBe(title)
    })
    it('update file', async () => {
      const content = 'test'
      const txtPath = path.resolve(tempPath, 'test.txt')
      await writeFile(txtPath, content)
      await resourceApi.update({ id, data: createReadStream(txtPath) })
      const res = await resourceApi.fileByResourceId(id)
      expect(res.toString()).toBe(content)
    })
    it('update properties and file', async () => {
      const title = `new title ${Date.now()}`
      const content = 'test'
      const txtPath = path.resolve(tempPath, 'test.txt')
      await writeFile(txtPath, content)
      const updateRes = await resourceApi.update({ id, title, data: createReadStream(txtPath) })
      expect(updateRes.title).toBe(title)
      const res = await resourceApi.fileByResourceId(id)
      expect(res.toString()).toBe(content)
    })
    it('update file only', async () => {
      const content = 'test'
      const txtPath = path.resolve(tempPath, 'test.txt')
      await writeFile(txtPath, content)
      const { title } = await resourceApi.get(id)
      await resourceApi.update({ id, data: createReadStream(txtPath) })
      const res = await resourceApi.fileByResourceId(id)
      expect(res.toString()).toBe(content)
      expect((await resourceApi.get(id)).title).toBe(title)
    })
  })
  /**
   * 已知错误
   * https://discourse.joplinapp.org/t/pre-release-v2-8-is-now-available-updated-14-april/25158/10?u=rxliuli
   */
  it.skip('test remove ', async () => {
    const id = (await createTestResource()).id
    await resourceApi.remove(id)
    await expect(resourceApi.get(id)).rejects.toThrowError()
  })
  it('test fileByResourceId', async () => {
    const res = await resourceApi.fileByResourceId(id)
    console.log(typeof res)
    const path = resolve(tempPath, 'resourcesByFileId.png')
    await writeFile(path, res)
    expect(pathExistsSync(path)).toBeTruthy()
  })
  it('test to get the size of the attachment resource', async () => {
    const id = (await createTestResource()).id
    const res = await resourceApi.get(id, ['id', 'title', 'size'])
    const stats = await stat(path.resolve(__dirname, '../resource/resourcesByFileId.png'))
    expect(res.size).toEqual(stats.size)
  })
})