Best JavaScript code snippet using playwright-internal
serve.js
Source:serve.js
1/**2 * Description: Serve a project3 * Author: Liam4 * CreatedAt: 2017-1216-12165 * UpdateBy:6 * UpdateAt:7 */ 8var webpack = require('webpack'),9 GMILOG = require ('../util/gmi-log'),10 chokidar = require ('chokidar')11// Generate webpack config object 12var CommonsChunkPlugin = require ("webpack/lib/optimize/CommonsChunkPlugin"),13 path = require ('path'),14 fs = require ('fs'),15 fsExtra = require ('fs-extra'),16 uglifyJsPlugin = webpack.optimize.UglifyJsPlugin,17 srcDir = path.resolve (process.cwd (), 'src'),18 distDir = path.resolve (process.cwd (), 'dist')19// Render Html20var glob = require ('glob'),21 minify = require ('html-minifier').minify22// Generate sass file23var sass = require ('node-sass')24if (fs.existsSync (path.resolve (process.cwd (), 'projectConfig.js'))) {25 var projectConfig = require (path.resolve (process.cwd (), 'projectConfig.js'))26}27// Express28var express = require ('express')29var app = express ()30var opener = require ('opener')31// RunServer Object32RunServer = module.exports = {}33RunServer.run = function () {34 RunServer.readyUp ()35 RunServer.startServe ()36}37RunServer.readyUp = function () {38 RunServer.webpackTool ()39 RunServer.renderHtml ()40 RunServer.renderSass ()41 RunServer.copyAssets ()42 // RunServer.copyJsLib ()43 RunServer.copyLib ()44 RunServer.watch ()45 // RunServer.copyScssLib ()46}47RunServer.startServe = function () {48 app.use (projectConfig.root, express.static (distDir))49 // app.get(projectConfig.root, function (req, res) {50 // res.send('Hello World')51 // res.redirect ('/')52 // })53 if (projectConfig) {54 app.listen (projectConfig.port)55 var browserObject = opener ("http://localhost:" + projectConfig.port + projectConfig.root)56 }57 // console.log (browserObject)58}59RunServer.localhost = function (port) {60 app.use ('/', express.static (path.resolve (process.cwd (), '')))61 app.listen (port)62 var browserTemp = opener ("http://localhost:" + port)63}64RunServer.renderSass = function () {65 setTimeout ( () => {66 sass.render ({67 file: 'src/scss/pages/main.scss',68 includePaths: ['src/scss/pages/'],69 outFile: 'dist/css',70 sourceMap: true,71 outputStyle: 'compressed',72 }, (error, result) => {73 if (error) {74 GMILOG.E_LOG (error)75 } else {76 fsExtra.outputFile ('dist/css/style.min.css', result.css, err => {77 if (err) console.log (err)78 })79 }80 })81 }, 500)82}83RunServer.renderHtml = function () {84 // console.log ("run render : " + srcDir + '/**/*.html')85 glob ('src/pages/**/*.html', {}, (err, files) => {86 // console.log (files)87 if (err) {88 console.log (err)89 }90 if (files.length < 1) {91 console.log ("no files")92 // return93 }94 files.forEach (path => {95 fs.readFile (path, 'utf8', (err, content) => {96 if (err) console.log (err)97 renderRecursive (path, content)98 })99 })100 })101}102RunServer.copyAssets = function () {103 fsExtra.copy ('src/assets/', 'dist/assets/', (err) => {104 if (err) console.log (err)105 console.log ("Assets" + " copied!") 106 })107}108RunServer.copyJsLib = function () {109 fsExtra.copy ('src/js/lib', 'dist/js/lib', (err) => {110 if (err) console.log (err)111 console.log ("js lib" + " copied!") 112 })113}114RunServer.copyLib = function () {115 fsExtra.copy ('src/lib', 'dist/lib', (err) => {116 if (err) console.log (err)117 console.log ("lib" + " copied!") 118 })119}120RunServer.copyScssLib = function () {121 fsExtra.copy ('src/scss/lib', 'dist/css/lib', (err) => {122 if (err) console.log (err)123 console.log ("scss lib" + " copied!") 124 })125}126/**127 * add 128 * unlink129 * unlinkDir130 * change131 * 132 */133RunServer.watch = function () {134 chokidar.watch ('src', {135 // ignored: /^src(\\|\/)js(\\|\/)pages.*\.js$/,136 ignoreInitial: true137 }).on ('all', (event, path) => {138 console.log (`event : ${event} ; path : ${path}`)139 if (/^src(\\|\/)js(\\|\/)pages.*\.js$/.test (path)) {140 console.log (path)141 if (event == "add" || event == "unlink") {142 RunServer.webpackTool (event)143 }144 } else if (/^src(\\|\/)pages.*\.html$/.test (path)) {145 console.log(path)146 RunServer.renderHtml ()147 } else if (/^src(\\|\/)scss(\\|\/)pages.*\.scss$/.test (path)) {148 RunServer.renderSass ()149 } else if (/^src(\\|\/)assets*/.test (path)) {150 console.log (path)151 if (event == "add") {152 fsExtra.copy (path, path.replace ('src', 'dist'), (err) => {153 if (err) console.log (err)154 console.log (path + " copied!") 155 })156 }157 } else if (/^src(\\|\/)lib.*\.js$/.test (path)) {158 if (event != "unlink" && event != "unlinkDir") {159 fsExtra.copy (path, path.replace ('src', 'dist'), (err) => {160 if (err) console.log (err)161 console.log (path + " copied!") 162 })163 }164 }165 })166}167RunServer.webpackTool = function (event) {168 if (event == "add" || event == "unlink") {169 if (RunServer.watching) {170 RunServer.watching.close (() => {171 console.log ("restart watch")172 })173 }174 if (RunServer.myDevConfig != null) {175 RunServer.myDevConfig = null176 }177 if (RunServer.devCompiler != null) {178 RunServer.devCompiler = null179 }180 var JsFileName = getJsFile (),181 EntryFileName = getEntryName ()182 //å建ä¸ä¸ªwebpacké
置对象183 RunServer.myDevConfig = Object.create ({184 //å
许ç¼åæé«æ§è½185 cache: true,186 //çæsourcemapæ件187 devtool: projectConfig.sourceMap || "cheap-module-eval-source-map",188 //å¤æ件å
¥å£189 entry: JsFileName,190 output: {191 //__dienameè¿åå½åæ件æå¨çè·¯å²192 path: path.resolve (distDir, 'js/'),193 //The publicPath specifies the public URL address of the output files when referenced in a browser.194 // the url to the output directory resolved relative to the HTML pageï¼ç½ç«è¿è¡æ¶è®¿é®çè·¯å¾195 publicPath: path.resolve (distDir, 'js/'),196 //çææ件çå½å197 filename: "[name].js",198 //æ¯æªè¢«åå¨entryä¸ï¼å´åéè¦è¢«æå
åºæ¥çæ件å½åé
ç½®,å¨æéå è½½ï¼å¼æ¥ï¼æ¨¡åçæ¶åï¼è¿æ ·çæ件æ¯æ²¡æ被åå¨entryä¸çï¼å¦ä½¿ç¨CommonJSçæ¹å¼å¼æ¥å 载模å199 /*200 require.ensure(["modules/tips.jsx"], function(require) {201 var a = require("modules/tips.jsx");202 // ...203 }, 'tips');204 å¼æ¥å è½½ç模åæ¯è¦ä»¥æ件形å¼å è½½å¦ï¼æ以è¿æ¶çæçæ件åæ¯ä»¥chunknameé
ç½®çï¼çæåºçæ件åå°±æ¯tips.min.jsã205 */206 chunkFilename: "[chunkhash].js"207 },208 resolve: {209 //æ¥æ¾moduleçè¯ä»è¿éå¼å§æ¥æ¾210 //root: '/pomy/github/flux-example/src', //ç»å¯¹è·¯å¾211 //èªå¨æ©å±æ件åç¼åï¼æå³çæ们require模åå¯ä»¥çç¥ä¸ååç¼å212 //extensions: ['', '.js', '.json', '.scss'],213 //模åå«åå®ä¹ï¼æ¹ä¾¿åç»ç´æ¥å¼ç¨å«åï¼æ é¡»å¤åé¿é¿çå°å214 alias: {215 // zepto: srcDir + "/js/lib/zepto.min.js",216 core: srcDir + "/js/core",217 util: srcDir + "/js/util",218 tool: srcDir + "/js/tool",219 }220 },221 module: {222 //å è½½å¨é
ç½®223 //解æåºzeptoçè·¯å¾ï¼ç¶å使ç¨å è½½å¨è¿è¡zeptoçæ¹å224 rules: [{225 test: /\.js$/,226 exclude: [/node_modules/],227 use: [{228 loader: 'babel-loader',229 options: {230 presets: ['es2015']231 }232 }],233 },234 // Loaders for other file types can go here235 ],236 },237 plugins: [238 new CommonsChunkPlugin ({name: 'common', chunks: EntryFileName}),239 new uglifyJsPlugin ({240 // æç´§åçè¾åº241 beautify: projectConfig.jsBeautify || true,242 // å é¤ææç注é243 comments: projectConfig.jsComments || false,244 compress: {245 // å¨UglifyJså é¤æ²¡æç¨å°ç代ç æ¶ä¸è¾åºè¦å246 warnings: projectConfig.jsWarnings || false,247 // å é¤ææç `console` è¯å¥248 // è¿å¯ä»¥å
¼å®¹ieæµè§å¨249 drop_console: projectConfig.jsDrop_console || false,250 // å
åµå®ä¹äºä½æ¯åªç¨å°ä¸æ¬¡çåé251 collapse_vars: projectConfig.jsCollapse_vars || false,252 // æååºåºç°å¤æ¬¡ä½æ¯æ²¡æå®ä¹æåéå»å¼ç¨çéæå¼253 reduce_vars: projectConfig.jsReduce_vars || false,254 }255 })256 ]257 //å½æ们æ³å¨é¡¹ç®ä¸requireä¸äºå
¶ä»çç±»åºæè
APIï¼èåä¸æ³è®©è¿äºç±»åºçæºç 被æ建å°è¿è¡æ¶æ件ä¸ï¼è¿å¨å®é
å¼åä¸å¾æå¿
è¦ãæ¤æ¶æ们就å¯ä»¥éè¿é
ç½®externalsåæ°æ¥è§£å³è¿ä¸ªé®é¢258 // externals: {259 // "jquery": "jQuery"260 // }261 })262 RunServer.devCompiler = webpack (RunServer.myDevConfig)263 RunServer.watching = RunServer.devCompiler.watch ({ // watch options:264 aggregateTimeout: 300, // wait so long for more changes265 poll: false // use polling instead of native watchers266 // pass a number to set the polling interval267 }, function (err, stats) {268 if (err) GMILOG.E_LOG (err)269 // GMILOG.N_LOG ("-")270 if (!RunServer.statsHash) {271 RunServer.statsHash = stats.hash272 GMILOG.N_LOG (stats.toString ({273 profile: true, colors: true274 }))275 } else {276 if (RunServer.statsHash != stats.hash) {277 GMILOG.N_LOG (stats.toString ({278 profile: true, colors: true279 })) 280 }281 }282 }) 283 } else {284 var JsFileName = getJsFile (),285 EntryFileName = getEntryName ()286 //å建ä¸ä¸ªwebpacké
置对象287 RunServer.myDevConfig = Object.create ({288 //å
许ç¼åæé«æ§è½289 cache: true,290 //çæsourcemapæ件291 devtool: projectConfig.sourceMap || "cheap-module-eval-source-map",292 //å¤æ件å
¥å£293 entry: JsFileName,294 output: {295 //__dienameè¿åå½åæ件æå¨çè·¯å²296 path: path.resolve (distDir, 'js/'),297 //The publicPath specifies the public URL address of the output files when referenced in a browser.298 // the url to the output directory resolved relative to the HTML pageï¼ç½ç«è¿è¡æ¶è®¿é®çè·¯å¾299 publicPath: path.resolve (distDir, 'js/'),300 //çææ件çå½å301 filename: "[name].js",302 //æ¯æªè¢«åå¨entryä¸ï¼å´åéè¦è¢«æå
åºæ¥çæ件å½åé
ç½®,å¨æéå è½½ï¼å¼æ¥ï¼æ¨¡åçæ¶åï¼è¿æ ·çæ件æ¯æ²¡æ被åå¨entryä¸çï¼å¦ä½¿ç¨CommonJSçæ¹å¼å¼æ¥å 载模å303 /*304 require.ensure(["modules/tips.jsx"], function(require) {305 var a = require("modules/tips.jsx");306 // ...307 }, 'tips');308 å¼æ¥å è½½ç模åæ¯è¦ä»¥æ件形å¼å è½½å¦ï¼æ以è¿æ¶çæçæ件åæ¯ä»¥chunknameé
ç½®çï¼çæåºçæ件åå°±æ¯tips.min.jsã309 */310 chunkFilename: "[chunkhash].js"311 },312 resolve: {313 //æ¥æ¾moduleçè¯ä»è¿éå¼å§æ¥æ¾314 //root: '/pomy/github/flux-example/src', //ç»å¯¹è·¯å¾315 //èªå¨æ©å±æ件åç¼åï¼æå³çæ们require模åå¯ä»¥çç¥ä¸ååç¼å316 //extensions: ['', '.js', '.json', '.scss'],317 //模åå«åå®ä¹ï¼æ¹ä¾¿åç»ç´æ¥å¼ç¨å«åï¼æ é¡»å¤åé¿é¿çå°å318 alias: {319 // zepto: srcDir + "/js/lib/zepto.min.js",320 core: srcDir + "/js/core",321 util: srcDir + "/js/util",322 tool: srcDir + "/js/tool"323 }324 },325 module: {326 //å è½½å¨é
ç½®327 //解æåºzeptoçè·¯å¾ï¼ç¶å使ç¨å è½½å¨è¿è¡zeptoçæ¹å328 rules: [{329 test: /\.js$/,330 exclude: [/node_modules/],331 use: [{332 loader: 'babel-loader',333 options: {334 presets: ['es2015']335 }336 }],337 },338 // Loaders for other file types can go here339 ],340 },341 plugins: [342 new CommonsChunkPlugin ({name: 'common', chunks: EntryFileName}),343 new uglifyJsPlugin ({344 // æç´§åçè¾åº345 beautify: projectConfig.jsBeautify || true,346 // å é¤ææç注é347 comments: projectConfig.jsComments || false,348 compress: {349 // å¨UglifyJså é¤æ²¡æç¨å°ç代ç æ¶ä¸è¾åºè¦å350 warnings: projectConfig.jsWarnings || false,351 // å é¤ææç `console` è¯å¥352 // è¿å¯ä»¥å
¼å®¹ieæµè§å¨353 drop_console: projectConfig.jsDrop_console || false,354 // å
åµå®ä¹äºä½æ¯åªç¨å°ä¸æ¬¡çåé355 collapse_vars: projectConfig.jsCollapse_vars || false,356 // æååºåºç°å¤æ¬¡ä½æ¯æ²¡æå®ä¹æåéå»å¼ç¨çéæå¼357 reduce_vars: projectConfig.jsReduce_vars || false,358 }359 })360 ]361 //å½æ们æ³å¨é¡¹ç®ä¸requireä¸äºå
¶ä»çç±»åºæè
APIï¼èåä¸æ³è®©è¿äºç±»åºçæºç 被æ建å°è¿è¡æ¶æ件ä¸ï¼è¿å¨å®é
å¼åä¸å¾æå¿
è¦ãæ¤æ¶æ们就å¯ä»¥éè¿é
ç½®externalsåæ°æ¥è§£å³è¿ä¸ªé®é¢362 // externals: {363 // "jquery": "jQuery"364 // }365 })366 RunServer.devCompiler = webpack (RunServer.myDevConfig)367 RunServer.watching = RunServer.devCompiler.watch ({ // watch options:368 aggregateTimeout: 300, // wait so long for more changes369 poll: false // use polling instead of native watchers370 // pass a number to set the polling interval371 }, function (err, stats) {372 if (err) GMILOG.E_LOG (err)373 // GMILOG.N_LOG ("-")374 if (!RunServer.statsHash) {375 RunServer.statsHash = stats.hash376 GMILOG.N_LOG (stats.toString ({377 profile: true, colors: true378 }))379 } else {380 if (RunServer.statsHash != stats.hash) {381 GMILOG.N_LOG (stats.toString ({382 profile: true, colors: true383 })) 384 }385 }386 }) 387 }388 // RunServer.devCompiler.run ((err, stats) => {389 // if (err) GMILOG.E_LOG (err)390 // // GMILOG.N_LOG ("-")391 // if (!RunServer.statsHash) {392 // RunServer.statsHash = stats.hash393 // GMILOG.N_LOG (stats.toString ({394 // profile: true, colors: true395 // }))396 // } else {397 // if (RunServer.statsHash != stats.hash) {398 // GMILOG.N_LOG (stats.toString ({399 // profile: true, colors: true400 // })) 401 // }402 // }403 // }) 404}405function renderRecursive (path, content) {406 // console.log (content + "\n-------" + path)407 let regexOuter = /<\%\ \@\@include="(.*?)"\ \%>/408 let regexInclude = /include="(.*?)"/409 let regexInner = />(.*?)</410 let rootReg = /\@PATH\@/411 let versionReg = /\@VERSION\@/412 // let COMMENT_PSEUDO_COMMENT_OR_LT_BANG = new RegExp(413 // '<!--[\\s\\S]*?(?:-->)?'414 // + '<!---+>?' // A comment with no body415 // + '|<!(?![dD][oO][cC][tT][yY][pP][eE]|\\[CDATA\\[)[^>]*>?'416 // + '|<[?][^>]*>?', // A pseudo-comment417 // 'g');418 let cleanComment = /\<\!\-\-(\ |)(.*?)\-\-\>/419 while (cleanComment.test (content)) {420 content = content.replace (cleanComment, '')421 }422 // while (COMMENT_PSEUDO_COMMENT_OR_LT_BANG.test (content)) {423 // content = content.replace (COMMENT_PSEUDO_COMMENT_OR_LT_BANG, '')424 // }425 content = content.replace (regexOuter, match => {426 let matchInclude = match427 let contentUpdated = ''428 // console.log (content)429 // console.log (matchInclude)430 match.replace (regexInclude, match => {431 // console.log (match)432 match.replace (/"(.*?)"/, matchIncludeFile => {433 let includeFileName = matchIncludeFile.substring (1, matchIncludeFile.length - 1)434 // console.log (path)435 let pathRelative = path.split ('/').slice (0, -1).join ('/')436 // console.log (pathRelative)437 if (/^\//.test (includeFileName)) {438 includeFileName = includeFileName.replace (/^\//, '')439 pathRelative = "src/pages"440 }441 if (/^includes\//.test (includeFileName)) {442 includeFileName = includeFileName.replace (/^includes\//, '')443 pathRelative = "src/pages/includes"444 }445 while (true) {446 if (/^\.\//.test (includeFileName)) {447 includeFileName = includeFileName.replace (/^\.\//, '')448 } else {449 break450 }451 }452 while (true) {453 if (/^\.\.\//.test (includeFileName)) {454 includeFileName = includeFileName.replace (/^\.\.\//, '')455 pathRelative = pathRelative.split ('/').slice (0, -1).join ('/')456 } else {457 break458 }459 }460 // console.log (includeFileName)461 // includeFileName.replace (/^\.\//, currentPath => {462 // console.log (currentPath)463 // })464 // console.log (includeFileName)465 let includeFilePath = pathRelative + "/" + includeFileName466 // contentUpdated = ' ' + matchInclude.replace (regexOuter, '').trim ()467 contentUpdated = matchInclude.replace (regexOuter, match => {468 let content = ''469 // console.log (includeFilePath)470 if (!fs.existsSync (includeFilePath)) {471 GMILOG.E_LOG (includeFilePath + " File not found!")472 } else {473 content = fs.readFileSync (includeFilePath, 'utf8')474 return '' + content + ''475 }476 })477 })478 })479 return contentUpdated480 })481 // console.log (content + "\n-------" + path)482 // console.log (/<\%\ \@\@include="(.*?)"\ \%>/.test (content))483 if (/<\%\ \@\@include="(.*?)"\ \%>/.test (content)) {484 renderRecursive (path, content)485 } else {486 let filename = path.replace (/^src/, 'dist').replace (/pages\//, '')487 while (versionReg.test (content)) {488 content = content.replace (versionReg, projectConfig.version)489 }490 while (rootReg.test (content)) {491 content = content.replace (rootReg, projectConfig.root)492 }493 // console.log (filename)494 fsExtra.outputFile (filename, minify (content, {collapseWhitespace: true, removeComments: true}), err => {495 if (err) console.log (err)496 })497 }498}499//è·åææjs\pagesç®å½ä¸çæ件夹å称500function getDirName () {501 var fileList = []502 var jsPath = path.resolve (srcDir, 'js/pages')503 // GMILOG.N_LOG (jsPath);504 if (!fs.existsSync (jsPath)) {505 GMILOG.E_LOG (jsPath + " is not exist!")506 } else {507 var dirs = fs.readdirSync (jsPath)508 dirs.forEach (function (item) {509 fileList.push (item)510 })511 }512 // GMILOG.N_LOG (fileList);513 return fileList514}515//éåè·åjsæ件çæ°ç»516function getJsFile () {517 //è·åjsç®å½ä¸æææ件夹ååæ°ç»518 var fileList = getDirName ()519 var totalFiles = {}520 var matchs = [],521 files = {}522 if (fileList.length > 0) {523 fileList.forEach (function (fileItem) {524 if (fileItem.match (/(.+)\.js$/)) {525 matchs = fileItem.match (/(.+)\.js$/)526 if (matchs) {527 files[matchs[1]] = path.resolve (srcDir, 'js/pages', fileItem)528 }529 } else {530 var jsPath = path.resolve (srcDir, 'js/pages/' + fileItem)531 // if (!fs.existsSync (jsPath)) {532 // GMILOG.E_LOG (jsPath + " is not exist!")533 // } else {534 var dirs = fs.readdirSync (jsPath)535 dirs.forEach (function (item) {536 matchs = item.match (/(.+)\.js$/)537 if (matchs) {538 files[matchs[1]] = path.resolve (srcDir, 'js/pages/' + fileItem, item)539 }540 });541 // }542 }543 })544 }545 return files546 //synchronous read dir,return an array of filenames excluding '.' and '..'547 // console.log("this is detected js: " + dirs);548 //declare matchs array and file object will be used later549 //use reg match any.js file550}551//éåè·åjsæ件çæ°ç»552function getEntryName () {553 //è·åjsç®å½ä¸æææ件夹ååæ°ç»554 var fileList = getDirName ()555 var totalFiles = {}556 var entryName = []557 var matchs = [],558 files = {}559 if (fileList.length > 0) {560 fileList.forEach (function (fileItem) {561 if (fileItem.match (/(.+)\.js$/)) {562 matchs = fileItem.match (/(.+)\.js$/)563 if (matchs) {564 entryName.push (matchs[1]);565 }566 } else {567 var jsPath = path.resolve (srcDir, 'js/pages/' + fileItem)568 // if (!fs.existsSync (jsPath)) {569 // GMILOG.E_LOG (jsPath + " is not exist!")570 // } else {571 var dirs = fs.readdirSync (jsPath)572 dirs.forEach (function (item) {573 matchs = item.match (/(.+)\.js$/)574 if (matchs) {575 entryName.push (matchs[1])576 }577 })578 // }579 }580 })581 }582 return entryName;583 //synchronous read dir,return an array of filenames excluding '.' and '..'584 // console.log("this is detected js: " + dirs);585 //declare matchs array and file object will be used later586 //use reg match any.js file...
app-server-test.js
Source:app-server-test.js
...25 });26 }).to.throw(/FastBootAppServer must be provided with either a distPath or a downloader option, but not both/);27 });28 it("serves an HTTP 500 response if the app can't be found", function() {29 return runServer('not-found-server')30 .then(() => request('http://localhost:3000'))31 .then(response => {32 expect(response.statusCode).to.equal(500);33 expect(response.body).to.match(/No Application Found/);34 });35 });36 it("serves static assets", function() {37 return runServer('basic-app-server')38 .then(() => request('http://localhost:3000/assets/fastboot-test.js'))39 .then(response => {40 expect(response.statusCode).to.equal(200);41 expect(response.body).to.contain('"use strict";');42 })43 .then(() => request('http://localhost:3000/'))44 .then(response => {45 expect(response.statusCode).to.equal(200);46 expect(response.body).to.contain('Welcome to Ember');47 });48 });49 it("returns a 404 status code for non-existent assets", function() {50 return runServer('basic-app-server')51 .then(() => request('http://localhost:3000/assets/404-does-not-exist.js'))52 .then(response => {53 expect(response.statusCode).to.equal(404);54 expect(response.body).to.match(/Not Found/);55 })56 .then(() => request('http://localhost:3000/'))57 .then(response => {58 expect(response.statusCode).to.equal(200);59 expect(response.body).to.contain('Welcome to Ember');60 });61 });62 it("executes beforeMiddleware", function() {63 return runServer('before-middleware-server')64 .then(() => request('http://localhost:3000'))65 .then(response => {66 expect(response.statusCode).to.equal(418);67 expect(response.headers['x-test-header']).to.equal('testing');68 expect(response.body).to.equal(JSON.stringify({ send: 'json back'}));69 });70 });71 it("executes afterMiddleware when there is an error", function() {72 return runServer('after-middleware-server')73 .then(() => request('http://localhost:3000'))74 .then(response => {75 expect(response.body).to.not.match(/error/);76 expect(response.headers['x-test-header']).to.equal('testing');77 });78 });79 it("returns a 401 status code for non-authenticated request", function() {80 return runServer('auth-app-server')81 .then(() => request('http://localhost:3000/'))82 .then(response => {83 expect(response.statusCode).to.equal(401);84 expect(response.headers['www-authenticate']).equal('Basic realm=Authorization Required');85 })86 .then(() => request({ uri: 'http://localhost:3000/', headers: { 'Authorization': 'Basic dG9tc3Rlcjp6b2V5' }}))87 .then(response => {88 expect(response.statusCode).to.equal(200);89 expect(response.body).to.contain('Welcome to Ember');90 });91 });92 it("responds on the configured host and port", function() {93 return runServer('ipv4-app-server')94 .then(() => request('http://127.0.0.1:4100/'))95 .then((response) => {96 expect(response.statusCode).to.equal(200);97 expect(response.body).to.contain('Welcome to Ember');98 });99 });100 it("allows setting sandbox globals", function() {101 return runServer('sandbox-globals-app-server')102 .then(() => request('http://localhost:3000/'))103 .then((response) => {104 expect(response.statusCode).to.equal(200);105 expect(response.body).to.contain('Welcome to Ember from MY GLOBAL!');106 });107 });108 it("allows changing of distpath", function() {109 return runServer('dist-path-change-server')110 .then(() => request('http://localhost:3000/'))111 .then((response) => {112 expect(response.statusCode).to.equal(200);113 expect(response.body).to.contain('Welcome to Ember from MY GLOBAL!');114 });115 });116});117function runServer(name) {118 return new Promise((res, rej) => {119 let serverPath = path.join(__dirname, 'fixtures', `${name}.js`);120 server = fork(serverPath, {121 silent: true122 });123 server.on('error', rej);124 server.stdout.on('data', data => {125 if (data.toString().match(/HTTP server started/)) {126 res();127 }128 });129 server.stderr.on('data', data => {130 console.log(data.toString());131 });...
server.js
Source:server.js
...21let server;22// this function starts our server and returns a Promise.23// In our test code, we need a way of asynchronously starting24// our server, since we'll be dealing with promises there.25function runServer() {26 const port = process.env.PORT || 8080;27 return new Promise((resolve, reject) => {28 server = app.listen(port, () => {29 console.log(`Your app is listening on port ${port}`);30 resolve(server);31 }).on('error', err => {32 reject(err)33 });34 });35}36// like `runServer`, this function also needs to return a promise.37// `server.close` does not return a promise on its own, so we manually38// create one.39function closeServer() {40 return new Promise((resolve, reject) => {41 console.log('Closing server');42 server.close(err => {43 if (err) {44 reject(err);45 // so we don't also call `resolve()`46 return;47 }48 resolve();49 });50 });51}52// if server.js is called directly (aka, with `node server.js`), this block53// runs. but we also export the runServer command so other code (for instance, test code) can start the server as needed.54if (require.main === module) {55 runServer().catch(err => console.error(err));56};...
process.js
Source:process.js
1export function getAppProcesses() {2 return [3 {'name': 'web', 'cmd': 'python manage.py runserver 0.0.0.0:80', 'status': 1, 'id': '1'},4 {'name': 'web', 'cmd': 'python manage.py runserver 0.0.0.0:80', 'status': 1, 'id': '2'},5 {'name': 'web', 'cmd': 'python manage.py runserver 0.0.0.0:80', 'status': 1, 'id': '3'},6 {'name': 'web', 'cmd': 'python manage.py runserver 0.0.0.0:80', 'status': 1, 'id': '4'},7 {'name': 'web', 'cmd': 'python manage.py runserver 0.0.0.0:80', 'status': 1, 'id': '5'},8 {'name': 'web', 'cmd': 'python manage.py runserver 0.0.0.0:80', 'status': 1, 'id': '6'},9 {'name': 'web', 'cmd': 'python manage.py runserver 0.0.0.0:80', 'status': 1, 'id': '7'},10 {'name': 'web', 'cmd': 'python manage.py runserver 0.0.0.0:80', 'status': 1, 'id': '8'},11 {'name': 'web', 'cmd': 'python manage.py runserver 0.0.0.0:80', 'status': 1, 'id': '9'},12 {'name': 'web', 'cmd': 'python manage.py runserver 0.0.0.0:80', 'status': 1, 'id': '10'},13 {'name': 'web', 'cmd': 'python manage.py runserver 0.0.0.0:80', 'status': 1, 'id': '11'},14 {'name': 'web', 'cmd': 'python manage.py runserver 0.0.0.0:80', 'status': 1, 'id': '12'},15 {'name': 'web', 'cmd': 'python manage.py runserver 0.0.0.0:80', 'status': 1, 'id': '13'},16 {'name': 'web', 'cmd': 'python manage.py runserver 0.0.0.0:80', 'status': 1, 'id': '14'},17 {'name': 'web', 'cmd': 'python manage.py runserver 0.0.0.0:80', 'status': 1, 'id': '15'},18 {'name': 'web', 'cmd': 'python manage.py runserver 0.0.0.0:8000', 'status': 0, 'id': '16'}19 ]20}21export function getAppProcessTypes() {22 return [23 {'name': 'web'}, {'name': 'celery'}, {'name': 'cbeat'}, {'name': 'cron'}, {'name': 'sync1'}, {'name': 'sync2'}24 ]...
gulpfile.js
Source:gulpfile.js
1'use strict';2var gulp = require('gulp');3var rename = require('gulp-rename');4var sass = require('gulp-sass');5var cleanCSS = require('gulp-clean-css');6var uglify = require('gulp-uglify');7var os = require('os');8var spawn = require('child_process').spawn;9gulp.task('build-css', function() {10 return gulp.src('static/scss/style.scss')11 .pipe(sass())12 .pipe(cleanCSS({compatibility: 'ie8'}))13 .pipe(rename({ extname: '.min.css' }))14 .pipe(gulp.dest('static/css/'));15});16gulp.task('build-js', function() {17 return gulp.src('static/js/script.js')18 .pipe(uglify())19 .pipe(rename({ extname: '.min.js' }))20 .pipe(gulp.dest('static/js/'));21});22gulp.task('runserver', ['build-css', 'build-js'], function() {23 gulp.watch('static/scss/style.scss', ['build-css']);24 gulp.watch('static/js/script.js', ['build-js']);25 // Compatibility across all platforms26 const pythonPath = (os.platform() === 'win32' ? '/scripts/' : '/bin/') + 'python';27 var runserver = spawn(28 process.env['VIRTUAL_ENV'] + pythonPath, ['manage.py', 'runserver'], { stdio: 'inherit' }29 );30 runserver.on('close', function(code) {31 if(code !== 0) {32 console.error('Django runserver exited with error code: ' + code);33 } else {34 console.log('Django runserver exited normally.');35 }36 });...
test-sever.js
Source:test-sever.js
1const mockstarLocalServer = require('../../lib');2let runServer;3function start(opts = {}) {4 return new Promise((resolve, reject) => {5 mockstarLocalServer6 .findAvailablePort(9528)7 .then(port => {8 runServer = mockstarLocalServer.startServer(9 Object.assign({}, opts, {port: port}),10 (isSuccess, data) => {11 isSuccess ? resolve(data) : reject(data);12 },13 );14 })15 .catch(err => {16 reject(err);17 });18 });19}20function stop() {21 if (!runServer || typeof runServer.stop !== 'function') {22 return;23 }24 // let t1 = Date.now();25 runServer.stop(() => {26 // console.log('-close success-', Date.now() - t1);27 });28}29module.exports = {30 start: start,31 stop: stop,...
coalescing.js
Source:coalescing.js
1'use strict';2const runServer = function (port) {3 console.log(`Server running on port ${port}.`);4};5runServer(3000);6runServer();7const runServer = function (port = 3000) {8 console.log(`Server running on port ${port}.`);9};10const runServer = function (port = 3000) {11 port = port || 3000; //falsy12 console.log(`Server running on port ${port}.`);13};14runServer(4000);15runServer(undefined);16runServer(0); //falsy17const runServer = function (port = 3000) {18 port = port ?? 3000; //null or undefined19 console.log(`Server running on port ${port}.`);20};21runServer(4000);22runServer(undefined);...
shorthand.js
Source:shorthand.js
2const runServer = function (port = 3000) {3 port = port ?? 3000; //null or undefined4 console.log(`Server running on port ${port}.`);5};6runServer(4000);7runServer(undefined);8runServer(0); //falsy9let i = 5;10i = i + 1;11i += 1;12i++;13i = i + 2;14i += 2;15port = port + 3000;16port += 3000;17const runServer = function (port = 3000) {18 port ??= 3000; //null or undefined19 console.log(`Server running on port ${port}.`);20};21runServer(4000);22runServer(undefined);...
Using AI Code Generation
1const playwright = require('playwright');2const { runServer } = require('playwright/lib/server/playwrightServer');3(async () => {4 const server = await runServer();5 const browser = await playwright.chromium.connectOverCDP({6 endpointURL: server.wsEndpoint(),7 });8 const context = await browser.newContext();9 const page = await context.newPage();10 await page.screenshot({ path: 'example.png' });11 await browser.close();12 await server.close();13})();
Using AI Code Generation
1const server = require('playwright/test/lib/server/server');2const { runServer } = server;3const { chromium } = require('playwright');4(async () => {5 const browser = await chromium.launch();6 const context = await browser.newContext();7 const page = await context.newPage();8 await page.screenshot({ path: 'google.png' });9 await browser.close();10})();11runServer();12module.exports = {13 use: {14 },15};
Using AI Code Generation
1const { runServer } = require('@playwright/test/lib/server/server');2const server = await runServer({ port: 8080 });3console.log(server.PREFIX);4const { runBrowserServer } = require('@playwright/test/lib/server/browserServer');5const browserServer = await runBrowserServer('chromium');6console.log(browserServer.PREFIX);7const { runLauncher } = require('@playwright/test/lib/server/launcher');8const launcher = await runLauncher();9console.log(launcher.PREFIX);10const { runBrowserType } = require('@playwright/test/lib/server/browserType');11const browserType = await runBrowserType('chromium');12console.log(browserType.PREFIX);13const { runBrowserContext } = require('@playwright/test/lib/server/browserContext');14const browserContext = await runBrowserContext();15console.log(browserContext.PREFIX);16const { runBrowser } = require('@playwright/test/lib/server/browser');17const browser = await runBrowser('chromium');18console.log(browser.PREFIX);19const { runPage } = require('@playwright/test/lib/server/page');20const page = await runPage();21console.log(page.PREFIX);22const { runFrame } = require('@playwright/test/lib/server/frame');23const frame = await runFrame();24console.log(frame.PREFIX);25const { runElementHandle } = require('@playwright/test/lib/server/elementHandler');26const elementHandle = await runElementHandle();27console.log(elementHandle.PREFIX);28const { runJSHandle } = require('@playwright/test/lib/server/jsHandle');29const jsHandle = await runJSHandle();30console.log(jsHandle.PREFIX);31const { runConsoleMessage } = require('@playwright/test/lib/server/consoleMessage');32const consoleMessage = await runConsoleMessage();33console.log(consoleMessage.PREFIX);
Using AI Code Generation
1(async () => {2 const server = await runServer({3 args: [path.resolve(__dirname, 'server.js')],4 });5 await server.stop();6})();7const http = require('http');8const server = http.createServer((req, res) => {9 res.end('Hello World!');10});11server.listen(3000);
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!