Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【每日一题】- 2019-08-16 - 怎么在浏览器中操作本地的文件 #16

Closed
azl397985856 opened this issue Aug 15, 2019 · 1 comment
Assignees
Labels
Daily Question 每日一题

Comments

@azl397985856
Copy link
Owner

由于安全的限制,浏览器是不开放写文件的API的,即使提供也会有很多限制。

假如现在有这样一个需求,让你去实现一个类似vue-cli 3.0 的可视化脚手架工具。

现在有一个问题,浏览器是无法直接操作本地文件,在本地生成文件目录的,那么我如何实现这个功能呢?

@azl397985856 azl397985856 changed the title 【每日一题】- 2019-08-15 - 怎么在浏览器中操作本地的文件 【每日一题】- 2019-08-16 - 怎么在浏览器中操作本地的文件 Aug 15, 2019
@azl397985856 azl397985856 added the Daily Question 每日一题 label Aug 15, 2019
@azl397985856 azl397985856 added this to 待认领 in 每日一题认领区 Aug 15, 2019
@wuyuchang
Copy link
Contributor

wuyuchang commented Aug 16, 2019

一般来说,本地的开发工具做成可视化仍然是在本地进行命令操作,比如git、ng等。

在浏览器中客户端受安全限制不开放操作本地文件的接口,因为如果能操作的话,用户访问网站后,服务器就能随意操控客户端文件管理了,这样一来,用户不小心点开一个网址,电脑就有可能直接被黑。

浏览器没有接口操作本地文件,但是服务器可以操控服务器上的本地文件,因为服务器往往需要建立本地日志文件,生成图片等各种情况,而各种后端语言都提供相应的操作文件的方法以及执行命令行命令的方法。

作为开发工具可视化,工具往往运用在本地环境中,因此客户端和服务器往往是同一台电脑,因此我们可以通过在本地建立后端服务,并将操作文件和命令的方法做成接口,前端在请求该接口就能达到在浏览器中通过接口控制本地文件的目的了。

以下基于express脚手架进行操作文件和执行命令的示例。

const exec = require('child_process').exec
const fs = require('fs')
const express = require('express')
const app = express()

// 创建文件示例
app.post('/api/file/create', () => {
  fs.writeFile('test.txt', 'hello world', 'utf8', err => {
    app.send({err})
  })
})

// 执行 ng build --prod示例
app.post('/api/cmd/bundle', () => {
  exec('ng build --prod', { cwd: __dirname }, (err, stdout, stderr) => {
    // 将命令行执行结果返回到客户端
    app.send({err, stdout, stderr})
  })
})

app.listen(80, () => { console.log('server start up at port 80') })

客户端直接请求接口即可实现打包或创建文件的方式。
以上提供了基础示例,实际根据项目需求进行扩展和更改。

@azl397985856 azl397985856 moved this from 待认领 to 正在进行 in 每日一题认领区 Aug 16, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Daily Question 每日一题
Projects
Development

No branches or pull requests

2 participants