-
怎么用vue引入fs
2021-04-09 10:35:08我在vue项目中import fs from "fs"与let fs = require("fs")都没有效果,输出fs是一个空对象,使用fs.stat报错这不是一个方法。那我要怎么引入fs呢?</p> -
vue怎么使用fs_node.js中的fs.createReadStream方法使用说明
2020-12-20 05:33:34(可读流)语法:fs.createReadStream(path, [options])由于该方法属于fs模块,使用前需要引入fs模块(var fs= require(“fs”) )接收参数:path: (string) 欲读取的文件路径options : (object) 数组对象包含以下属性{ ...方法说明:
返回一个readStream(文件读取流,输入流)对象。(可读流)
语法:
fs.createReadStream(path, [options])
由于该方法属于fs模块,使用前需要引入fs模块(var fs= require(“fs”) )
接收参数:
path: (string) 欲读取的文件路径
options : (object) 数组对象包含以下属性
{ flags: 'r',
encoding: null,
fd: null,
mode: 0666,
autoClose: true
}
options 可以通过start 和 end 设置 文件 可读取的字节数范围,而不是读取整个文件。
如果start 和 end都被包含的情况下 ,将从0开始。
encodeing 可以是 ‘utf8′, ‘ascii', 或 ‘base64′三种格式。
如果autoClose为false时,文件描述符将不会被关闭,即使他们报错了。
最好把它关闭掉 并确保不会出现文件描述符泄漏。
如果autoClose为true时(默认的行为),对错误或结束的文件描述符将自动关闭。
例子:
该例子将读取一个100k的文件中的最后10十字节内容。
fs.createReadStream('sample.txt', {start: 90, end: 99});
源码:
fs.createReadStream = function(path, options) {
return new ReadStream(path, options);
};
-
vue2.0 cdn和webpack方式引入均报错
2020-11-28 02:33:48启动报fs和child_process未引入错误: <code>These dependencies were not found: * fs in ./~/mime/mime.js, ./~/ali-oss/lib/object.js and 3 others * child_process in ./~/address/lib/address.js To ... -
在vue中自动生成文件以及自动引入component,router、vuex按模块划分
2020-06-22 18:32:43作为一个经常偷懒的程序员,用vue写代码的时候怎么可以一个一个.vue文件创建和一个一个引入componet呢,下面是提交你开发效率的方法。 1.安装插件npm install chalk --save-dev 2.在根目录下创建一个scripts文件 ...作为一个经常偷懒的程序员,用vue写代码的时候怎么可以一个一个.vue文件创建和一个一个引入componet呢,下面是提交你开发效率的方法。
1.安装插件npm install chalk --save-dev
2.在根目录下创建一个scripts文件
代码如下:
generateVue.js// index.js const chalk = require('chalk') const path = require('path') const fs = require('fs') const resolve = (...file) => path.resolve(__dirname, ...file) const log = message => console.log(chalk.green(`${message}`)) const successLog = message => console.log(chalk.blue(`${message}`)) const errorLog = error => console.log(chalk.red(`${error}`)) // 导入模板 const { vueTemplate // entryTemplate } = require('./template') // 生成文件 const generateFile = (path, data) => { if (fs.existsSync(path)) { errorLog(`${path}文件已存在`) return } return new Promise((resolve, reject) => { fs.writeFile(path, data, 'utf8', err => { if (err) { errorLog(err.message) reject(err) } else { resolve(true) } }) }) } log('请输入要生成的vue文件夹名称 views: xxx、comp: xxx、pageComp: xxx、 它们会生成在对应的文件目录下') let componentName = '' process.stdin.on('data', async chunk => { // 组件名称 const inputName = String(chunk).trim().toString().split(':')[1] // 判断放在那个文件夹里面 let pathName = String(chunk).trim().toString().split(':')[0] switch (pathName) { case 'views': pathName = 'views' break case 'comp': pathName = 'components' break case 'pageComp': pathName = 'pageComponents' break } // Vue页面组件路径 const componentPath = resolve(`../src/${pathName}`, inputName) // vue文件 const vueFile = resolve(componentPath, 'index.vue') // 入口文件 // const entryFile = resolve(componentPath, 'entry.js') // 判断组件文件夹是否存在 const hasComponentExists = fs.existsSync(componentPath) if (hasComponentExists) { errorLog(`${inputName}页面组件已存在,请重新输入`) return } else { log(`正在生成 ${inputName} 的目录 ${componentPath}`) await dotExistDirectoryCreate(componentPath) if (pathName === 'views') { log(`正在生成页面子组件 components 的目录 ${componentPath}\\components`) await fs.mkdir(`${componentPath}\\components`, err => { log(err) }) } } try { // 获取组件名 if (inputName.includes('/')) { const inputArr = inputName.split('/') componentName = inputArr[inputArr.length - 1] } else { componentName = inputName } log(`正在生成 vue 文件 ${vueFile}`) await generateFile(vueFile, vueTemplate(componentName)) // log(`正在生成 entry 文件 ${entryFile}`) // await generateFile(entryFile, entryTemplate(componentName)) successLog('生成成功') } catch (e) { errorLog(e.message) } process.stdin.emit('end') }) process.stdin.on('end', () => { log('exit') process.exit() }) function dotExistDirectoryCreate(directory) { return new Promise((resolve) => { mkdirs(directory, function() { resolve(true) }) }) } // 递归创建目录 function mkdirs(directory, callback) { var exists = fs.existsSync(directory) if (exists) { callback() } else { mkdirs(path.dirname(directory), function() { fs.mkdirSync(directory) callback() }) } }
template.js
// template.js module.exports = { vueTemplate: compoenntName => { return `<template> <div class="${compoenntName}"></div> </template> <script> export default { name: '${compoenntName}', components: {}, mixins: [], props: {}, data() { return {} }, computed: {}, watch: {}, created() {}, mounted() {}, destroyed() {}, methods: {} } </script> <style lang="" scoped> .${compoenntName}{ } </style> ` } }
3.在package.json里面新建命令
"scripts": { "new:vue": "node ./scripts/generateVue" },
自动生成文件这样就做好了,下面来演示一下使用的方法:
npm run new:vue dist
可以看到在views文件夹下生成了test文件夹那么如何快速引入component呢? 下面介绍这种方法
在components文件夹下创建一个index.js负责全部导出
代码如下:const componentFiles = require.context('./', true, /\index.vue$/) const components = componentFiles.keys().reduce((files, filePath) => { const fileName = filePath.replace(/^\.\/(.*)\/index\.\w+$/, '$1') const value = componentFiles(filePath) files[fileName] = value.default return files }, {}) module.exports = components
注意,以上组件的格式必须要如下:按照vue推荐的格式规范文件夹名字命名单词大写开头。
然后再vue.config.js里面设置一下
1.npm install path --save
const path = require("path"); function resolve(dir) { return path.join(__dirname, dir); } module.exports = { chainWebpack: config => { config.resolve.alia .set('components', resolve('src/components/index.js')) }, }
然后在你需要使用组件的地方:
import { 文件名 } from 'components'
你看这样配合上刚刚自动生成文件是不是非常的方便。 哈哈哈router按模块划分
const routerFiles = require.context('./modules', true, /\.js$/) let routerList = [] routerFiles.keys().forEach((fileName) => { if (routerFiles(fileName).default instanceof Array) { routerList = routerList.concat(routerFiles(fileName).default) } else { routerList.push(routerFiles(fileName).default) } }) // 404 页面必须放在最后!!! const errorPage = { path: '*', redirect: '/404', hidden: true } routerList.push(errorPage) // 路由配置 const RouterConfig = { mode: 'history', base: process.env.BASE_URL, routes: routerList } const router = new VueRouter(RouterConfig)
文件格式如下:
const routers = [ { // 首页 path: '/', name: 'Home', components: { default: () => import('@/views/home/index.vue'), }, meta: {} } ]
vuex按模块划分
index.jsimport Vue from 'vue' import Vuex from 'vuex' import getters from './getters' Vue.use(Vuex) // https://webpack.js.org/guides/dependency-management/#requirecontext const modulesFiles = require.context('./modules', true, /\.js$/) // you do not need `import app from './modules/app'` // it will auto require all vuex module from modules file const modules = modulesFiles.keys().reduce((modules, modulePath) => { // set './app.js' => 'app' const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1') const value = modulesFiles(modulePath) modules[moduleName] = value.default return modules }, {}) const store = new Vuex.Store({ modules, getters }) export default store
getters.js
const getters = { themeColor: state => state.settings.color, // 获取主题颜色 export default getters
举个modules例子
import { findTabMenu } from '@/http/api.js' /* 设置模块 */ const state = { stepsActive: -1, // 步骤条激活步骤 Number color: '#1BA79A', // 主题颜色 } const mutations = { } const actions = { } export default { namespaced: true, // 每个模块都需要添加 namespaced: true state, mutations, actions }
这样就封装好了,至于按模块划分的vuex使用方法,以后有时间再补充一下
-
Vue cli别名配置
2020-04-25 20:53:39新建一个vue.config.js文件,这个文件的作用有:配置别名、配置一些插件像scss-resources-loader:一个可以创建多个文件,文件内部的内容都会作为全局变量,在其他创建的文件中不用引入可以直接访问、以及其他插件。...Vue cli别名配置
- 新建一个
vue.config.js
文件,这个文件的作用有:配置别名
、配置一些插件
像scss-resources-loader
:一个可以创建多个文件,文件内部的内容都会作为全局变量,在其他创建的文件中不用引入可以直接访问
、以及其他插件。 - 配置内容
const path = require('path'); const fs = require('fs'); function resolve(dir) { // 拿到文件的函数 return path.join(__dirname, dir);// 将当前文件和dir参数的路径自动合并成为正确的路径 } module.exports = { // 主体 configureWebpack: { resolve: { alias: { // 别名配置 'views': '@/views', // 这里是views文件夹的路径 src/views 'components': '@/components' // 这里是components文件夹的路径 src/components } } }, chainWebpack: config => { // 这里的config拿到的是configureWebpack config.resolve.alias // 这个自然就是别名配置了 // src内部路径 .set('@$', resolve('src')) // 设置@表示src文件夹 // components内部路径 .set('components', resolve('src/components')) // 设置components表示src/components // views路径 .set('views', resolve('src/views')); // 设置views表示src/views } }
- 可能有时候配置是正确的但是仍然无法正确访问路径,最好办法建议这时候可以使用
@/...
来访问你的文件,@/xxx
访问路径目前没有出过问题。
good study and everyday up.——coderNoob
- 新建一个
-
electron-vue 更新踩坑
2020-02-11 14:50:25electron-vue 更新踩坑 新建一个update.js文件 首先引入electron-updater,没装的就npm install下 import { autoUpdater } from 'electron-updater' //因为要和渲染器进程通信 所以引入 import { ipcMain } from '...electron-vue 更新踩坑
新建一个update.js文件
首先引入electron-updater,没装的就npm install下import { autoUpdater } from 'electron-updater' //因为要和渲染器进程通信 所以引入 import { ipcMain } from 'electron' const fs = require('fs-extra') const path = require('path') const log = require('electron-log') //日志打印方便查看 //定义状态 const MESSAGE = { error: { status: 0, text: '检查更新出错' }, checking: { status: 1, text: '正在检查更新……' }, updateAva: { status: 2, text: '检测到新版本' }, updateNotAva: { status: 3, text: '现在使用的就是最新版本,不用更新' } }
贴上主要代码
class Update { //将该窗口对象作为参数 constructor(mainWindow) { this.mainWindow = mainWindow this.updaterCacheDir = 'xxxx' //更新下载产生的文件目录名 要与packjson 里的name 一致 this.uploadUrl = 'xxxx'; //更新服务器的地址 this.init() this.onError() this.onCheckUpdate() this.onCheckFound() this.onNoCheckFound() this.onDownloadProcess() this.onUpdateComplate() this.onDownload() } sendUpdateMessage(text) { this.mainWindow.webContents.send('message', text) } init() { autoUpdater.setFeedURL(this.uploadUrl) autoUpdater.autoDownload = false log.transports.console.level = false log.transports.console.level = 'silly' autoUpdater.logger = log const updatePendingPath = path.join(autoUpdater.app.baseCachePath, this.updaterCacheDir, 'pending') fs.emptyDir(updatePendingPath) // 每次打开软件时候清空下载更新的目录 log.warn('下载的更新目录缓存地址:' + updatePendingPath) } onError() { autoUpdater.on('error', error=> { this.sendUpdateMessage(MESSAGE.error) }) } onCheckUpdate() { autoUpdater.on('checking-for-update', _=>{ log.warn('触发检查更新') this.sendUpdateMessage(MESSAGE.checking) }) } onCheckFound() { autoUpdater.on('update-available', info=> { log.warn('检测到新版本') this.sendUpdateMessage(MESSAGE.updateAva) }) } onNoCheckFound() { autoUpdater.on('update-not-available',info=>{ this.sendUpdateMessage(MESSAGE.updateNotAva) }) } // 更新下载进度事件 onDownloadProcess() { autoUpdater.on('download-progress', progressObj=> { log.warn(progressObj) this.mainWindow.webContents.send('downloadProgress', progressObj) }) } onUpdateComplate() { autoUpdater.on('update-downloaded', (event, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate)=> { ipcMain.on('isUpdateNow', (e, arg) => { autoUpdater.quitAndInstall() this.mainWindow.destroy() }) this.mainWindow.webContents.send('isUpdateNow') }) } onDownload() { ipcMain.on('downloadUpdate', () => { log.warn('触发下载') autoUpdater.downloadUpdate() }) } } export default Update
回到主进程的js文件里引入
import Update from 'xxxx' new Update(mainWindow);
回到渲染页面 App.vue引入 ipcRenderer 进行监听就行了
ui用的element-ui 就不贴代码了很简单注意事项
1.之前一只在本地运行项目 我说怎么触发的更新事件都是报错 原来是要打包好了运行才可以正常触发
2.就是注意下electron的版本 之前是老版本1.x.x的版本 也是报错 后面更新到^3.0.0就ok了,还有electron-updater 的版本我这里是^4.1.2 -
vue-cli3.x版本 vue.config.js配置
2020-06-19 17:02:05const fs = require("fs"); //操作本地文件,多用于构建多项目,按需引入 const path = require("path"); const CopyWebpackPlugin = require("copy-webpack-plugin"); //copy静态文件,按需引入 const ... -
E:\git\my-vue-scaffold\node_modules\memory-fs\lib\MemoryFileSystem.js:114 throw new ...
2020-11-22 10:53:57<div><p>引入vue-skeleton-webpack-plugin插件,执行,却报memory-fs读取不到文件,显示file不存在,排查了一下最终生成的webpack.skeleton.conf生成的对象,如下: <code>{ ... -
vue路由require方法_不用vuejs的路由懒加载,直接用require引入文件,为什么不起作用?能帮忙解决吗...
2021-01-17 18:43:04const path = require('path')const HTMLPlugin = require('html-webpack-plugin')const webpack = require('webpack')const ExtractPlugin = require('extract-text-webpack-plugin')const fs = require('fs');... -
const svg = await fs.readFile(input, 'utf8'); const canvas = preset.createCanvas(800, 600); const ctx = canvas.getContext('2d'); const v = Canvg.fromString(ctx, svg, preset); // Render only ...
-
electron-vue+dialog保存base64图片
2020-12-22 13:59:23引入fs模块 去除base64 "data:image;base64," 获取保存路径 保存文件 const {dialog} = require("electron").remote const fs = require("fs") let base64 = result.data.replace(/^data:image\/\w+;base64,/,... -
vue3.0加MongoDB加node的后台管理系统(四)
2021-02-24 15:59:20引入fs模块用于与文件系统进行交互 npm install formidable npm install fs const fs = require('fs') const formidable = require('formidable') 然后定义上传接口 //上传头像接口 router.post('/file_upload', ... -
vue打包上传到腾讯COS
2019-11-15 16:15:361, 引入cos-nodejs-sdk-v5 npm i cos-nodejs-sdk-v5 --save 2,在build文件下创建uploadOSS.js let COS = require('cos-nodejs-sdk-v5') var fs = require('fs'); var delList = [] var bucket = 'myBucket... -
vue打包上传到阿里OSS
2019-11-15 16:26:301, 引入ali-oss npm i ali-oss --save 2,在build文件下创建uploadOSS.js let OSS = require('ali-oss') var fs = require('fs'); var delList = [] var bucket = '' if (process.env.env_config==='test'... -
vue+elementUI实现不同主题的切换(切换功能)
2021-04-06 17:36:58今天闲的很,借鉴vue-admin,搭了个可以切换不同主题颜色的前端框架(vue+elementUI) 主要逻辑就是依靠gulp生成不同主题的静态css文件(element-theme-chalk就是靠这个的) 切换主题的时候,引入不同的静态css... -
nodejs+mongodb+vue前后台配置ueditor的示例代码
2020-12-23 07:22:49笔者在做一个个人博客项目的时候需要一个富文本框输入组件与后台进行交互,但是官方配置里面没有关于nodejs的,于是自己查阅资料研究了一下,最后终于应用到了系统中。...const fs = require('fs'); //引入处理路 -
关于Vue移动端ui组件lib-flexible的转换问题
2018-09-19 11:43:30在Vue的移动端中有很多ui组件,比如:vux、mint-ui、muse-ui等。但是直接引入到项目中会遇到lib-flexible的转换问题 这个问题的解决在网上暂时没找到好的 ,但是有一个可以解决就是改vux、mint-ui、... -
vue前后端交互(router路由逻辑笔记)
2020-05-17 10:31:43黑马程序员笔记:::::: // 引入json文件测试 ...const fs = require('fs'); // 自动生成图书编号(自增) let maxBookCode = () => { let arr = []; data.forEach((item) => { arr.push(it -
vue+axios+express+multer 在express使用multer上传和下载图片
2019-08-09 00:14:132. 引入,还需要引入node中原生的2个模块(无需安装)-----node中 var multer = require('multer'); let fs = require("fs"); let path = require("path"); 3. 写接口-----node中 //上传接口 ... -
nuxt.js 项目中局部引入时导致打包报错
2021-01-03 09:08:13局部引入vue-baidu-map,运行nuxt.js的npm run generate和npm run build时报错,全局引入将不会报错 </code></pre> 完整异常信息 <pre><code> ERROR in 11.266400bed3682216b91b.js from UglifyJs ... -
在 node 中使用es6的模块导入方式
2020-09-24 11:31:57vue 写多了 就喜欢使用 import 的方式 引入 模块 进行使用 但是把 nodeJs 是 CommonJS 的模块规范 正常使用的话 是 const fs = require('fs'); console.log( fs ); 然后使用 node 运行一下 然后这下 我们直接更换... -
dd命令 创建文件并写入数据_npm命令行创建文件夹和文件
2021-01-31 16:18:06很多时候我们新建文件的时候,手动添加似乎有点麻烦,大部分人都想使用一条命令行执行就可以创建出想要的文件夹以及其基本内容,如:以上是执行了... //fs是node.js的核心模块,不用下载安装,可以直接引入1. fs.sta... -
js根据本地文件路径上传文件(流上传)
2021-02-07 14:47:29var fs = require('fs') //需要引入nodejs中的文件操作部分 var http = require('http') //需要引入nodejs中http请求部分 /** * 实际封装接口的入口 * @param {*} options 请求的配置项 * @param {*} path 文件... -
小tips:node起一个简单服务,打开本地项目或文件浏览
2018-03-07 16:44:001、安装nodejs 2、在项目文件夹目录下创建一个js文件,命名server.js(自定义名称)...var fs = require('fs');//引入文件读取模块 var documentRoot = 'D:/test/prerender-spa-plugin/examples/vue2-webpack-rout... -
记录使用electron软件热更新
2020-12-25 20:42:51使用vue打包的项目,放在electron生成的外壳中,当项目启动时检测软件有没有更新,如果有则从线上下载更新文件的压缩包,解压至本地,解压完之后删除安装包,然后项目重启 安装 因为是直接借用的外壳,还需要下载... -
webpack项目出现This dependency was not found:解决方法
2018-03-17 00:16:00在vue项目中我需要写一个爬虫,在引入node.js 中的 var request = require('request'); 时发现报如下的错误 但是重新下载多次fs模块都没有解决问题。 后来才发现是webpack的神坑 这个解决办法是: ... -
关于用户登录与鉴权事宜
2020-12-01 17:28:51举例 https://www.keycloak.org/2017/03/how-to-setup-ms-ad-fs-30-as-brokered-identity-provider-in-keycloak.html</p> 我自己已测试的点 <ul><li>powerjob-server 添加spring security,keycloak starter... -
跨项目区块复用方案实践
2020-12-08 23:39:39<p><strong>一个 React, Vue or Angular 组件</strong></p> </li><li> <p><strong>公共样式文件 (例如 CSS, SCSS)</strong></p> </li><li> <p><strong>可复用的方法</strong></p> </li></ul> 针对每个组件 Bit 主要...