How to use fileExistsSync method in Nightwatch

Best JavaScript code snippet using nightwatch

js-yaml-loaderSpec.js

Source:js-yaml-loaderSpec.js Github

copy

Full Screen

...223 describe('load plugins by relative path property', () => {224 let config225 beforeAll(() => {226 const fileMock = {227 fileExistsSync() {228 return true229 }230 }231 const fsMock = {232 readFileSync(filePath) {233 if (filePath === './config.json') {234 return `{235 "plugins": {236 "logger": {237 "path": "./logger"238 },239 "message": {240 "path": "./message",241 "options": { "foo": 3, "bar": 4 }242 }243 }244 }`245 } else {246 throw new Error(`should not require any other file: ${filePath}`)247 }248 }249 }250 const loggerModule = function (options) { return options }251 loggerModule['@noCallThru'] = true252 loggerModule['@global'] = true253 class MessageModule { constructor(options) { this.options = options }}254 MessageModule['@noCallThru'] = true255 MessageModule['@global'] = true256 const configLoader = proxyquire('../../src/config/js-yaml-loader', {257 fs: fsMock,258 './file-utils': fileMock,259 [path.resolve('./logger')]: loggerModule,260 [path.resolve('./message')]: MessageModule261 })262 config = configLoader.loadConfig(null, { config: './config.json' }).config263 })264 it('load plugins', () => {265 expect(config.messageConnector.options).toEqual({ foo: 3, bar: 4 })266 })267 })268 describe('load plugins by path property (npm module style)', () => {269 let config270 beforeAll(() => {271 const fileMock = {272 fileExistsSync() {273 return true274 }275 }276 const fsMock = {277 readFileSync(filePath) {278 if (filePath === './config.json') {279 return `{280 "plugins": {281 "cache": {282 "path": "foo-bar-qox",283 "options": { "foo": 3, "bar": 4 }284 }285 }286 }`287 } else {288 throw new Error(`should not require any other file: ${filePath}`)289 }290 }291 }292 class FooBar {293 constructor(options) { this.options = options }294 }295 FooBar['@noCallThru'] = true296 FooBar['@global'] = true297 const configLoader = proxyquire('../../src/config/js-yaml-loader', {298 fs: fsMock,299 './file-utils': fileMock,300 'foo-bar-qox': FooBar301 })302 config = configLoader.loadConfig(null, { config: './config.json' }).config303 })304 it('load plugins', () => {305 expect(config.cache.options).toEqual({ foo: 3, bar: 4 })306 })307 })308 describe('load plugins by name with a name convention', () => {309 let config310 beforeAll(() => {311 const fileMock = {312 fileExistsSync() {313 return true314 }315 }316 const fsMock = {317 readFileSync(filePath) {318 if (filePath === './config.json') {319 return `{320 "plugins": {321 "message": {322 "name": "super-messager",323 "options": { "foo": 5, "bar": 6 }324 },325 "storage": {326 "name": "super-storage",327 "options": { "foo": 7, "bar": 8 }328 }329 }330 }`331 } else {332 throw new Error(`should not require any other file: ${filePath}`)333 }334 }335 }336 class SuperMessager {337 constructor(options) { this.options = options }338 }339 SuperMessager['@noCallThru'] = true340 SuperMessager['@global'] = true341 class SuperStorage {342 constructor(options) { this.options = options }343 }344 SuperStorage['@noCallThru'] = true345 SuperStorage['@global'] = true346 const configLoader = proxyquire('../../src/config/js-yaml-loader', {347 fs: fsMock,348 './file-utils': fileMock,349 'deepstream.io-msg-super-messager': SuperMessager,350 'deepstream.io-storage-super-storage': SuperStorage351 })352 config = configLoader.loadConfig(null, {353 config: './config.json'354 }).config355 })356 it('load plugins', () => {357 expect(config.messageConnector.options).toEqual({ foo: 5, bar: 6 })358 expect(config.storage.options).toEqual({ foo: 7, bar: 8 })359 })360 })361 describe('load plugins by name with a name convention with lib prefix', () => {362 let config363 beforeAll(() => {364 const fileMock = {365 fileExistsSync() {366 return true367 }368 }369 const fsMock = {370 readFileSync(filePath) {371 if (filePath === './config.json') {372 return `{373 "plugins": {374 "message": {375 "name": "super-messager",376 "options": { "foo": -1, "bar": -2 }377 },378 "storage": {379 "name": "super-storage",380 "options": { "foo": -3, "bar": -4 }381 }382 }383 }`384 } else {385 throw new Error(`should not require any other file: ${filePath}`)386 }387 }388 }389 class SuperMessager {390 constructor(options) { this.options = options }391 }392 SuperMessager['@noCallThru'] = true393 SuperMessager['@global'] = true394 class SuperStorage {395 constructor(options) { this.options = options }396 }397 SuperStorage['@noCallThru'] = true398 SuperStorage['@global'] = true399 const configLoader = proxyquire('../../src/config/js-yaml-loader', {400 fs: fsMock,401 './file-utils': fileMock,402 [path.resolve(process.cwd(), 'foobar', 'deepstream.io-msg-super-messager')]: SuperMessager,403 [path.resolve(process.cwd(), 'foobar', 'deepstream.io-storage-super-storage')]: SuperStorage404 })405 config = configLoader.loadConfig(null, {406 config: './config.json',407 libDir: 'foobar'408 }).config409 })410 it('load plugins', () => {411 expect(config.messageConnector.options).toEqual({ foo: -1, bar: -2 })412 expect(config.storage.options).toEqual({ foo: -3, bar: -4 })413 })414 })415 describe('load plugins by name with a name convention with an absolute lib prefix', () => {416 let config417 beforeAll(() => {418 const fileMock = {419 fileExistsSync() {420 return true421 }422 }423 const fsMock = {424 readFileSync(filePath) {425 if (filePath === './config.json') {426 return `{427 "plugins": {428 "message": {429 "name": "super-messager",430 "options": { "foo": -1, "bar": -2 }431 },432 "storage": {433 "name": "super-storage",...

Full Screen

Full Screen

create.js

Source:create.js Github

copy

Full Screen

...71 fse.mkdirsSync(tmpDir);72 process.chdir(tmpDir);73 create.options.template = 'aws-nodejs';74 return create.create().then(() => {75 expect(create.serverless.utils.fileExistsSync(path.join(tmpDir, 'serverless.yml')))76 .to.be.equal(true);77 expect(create.serverless.utils.fileExistsSync(path.join(tmpDir, 'handler.js')))78 .to.be.equal(true);79 expect(create.serverless.utils.fileExistsSync(path.join(tmpDir, '.gitignore')))80 .to.be.equal(true);81 process.chdir(cwd);82 });83 });84 it('should generate scaffolding for "aws-python" template', () => {85 const cwd = process.cwd();86 fse.mkdirsSync(tmpDir);87 process.chdir(tmpDir);88 create.options.template = 'aws-python';89 return create.create().then(() => {90 expect(create.serverless.utils.fileExistsSync(path.join(tmpDir, 'serverless.yml')))91 .to.be.equal(true);92 expect(create.serverless.utils.fileExistsSync(path.join(tmpDir, 'handler.py')))93 .to.be.equal(true);94 expect(create.serverless.utils.fileExistsSync(path.join(tmpDir, '.gitignore')))95 .to.be.equal(true);96 process.chdir(cwd);97 });98 });99 it('should generate scaffolding for "aws-java-maven" template', () => {100 const cwd = process.cwd();101 fse.mkdirsSync(tmpDir);102 process.chdir(tmpDir);103 create.options.template = 'aws-java-maven';104 return create.create().then(() => {105 expect(create.serverless.utils.fileExistsSync(path.join(tmpDir, 'serverless.yml')))106 .to.be.equal(true);107 expect(create.serverless.utils.fileExistsSync(path.join(tmpDir, 'event.json')))108 .to.be.equal(true);109 expect(create.serverless.utils.fileExistsSync(path.join(tmpDir, 'pom.xml')))110 .to.be.equal(true);111 expect(create.serverless.utils.fileExistsSync(path.join(tmpDir, 'src', 'main', 'java',112 'hello', 'Handler.java'113 )))114 .to.be.equal(true);115 expect(create.serverless.utils.fileExistsSync(path.join(tmpDir, 'src', 'main', 'java',116 'hello', 'Request.java'117 )))118 .to.be.equal(true);119 expect(create.serverless.utils.fileExistsSync(path.join(tmpDir, 'src', 'main', 'java',120 'hello', 'Response.java'121 )))122 .to.be.equal(true);123 expect(create.serverless.utils.fileExistsSync(path.join(tmpDir, '.gitignore')))124 .to.be.equal(true);125 process.chdir(cwd);126 });127 });128 it('should generate scaffolding for "aws-java-gradle" template', () => {129 const cwd = process.cwd();130 fse.mkdirsSync(tmpDir);131 process.chdir(tmpDir);132 create.options.template = 'aws-java-gradle';133 return create.create().then(() => {134 expect(create.serverless.utils.fileExistsSync(path.join(tmpDir, 'serverless.yml')))135 .to.be.equal(true);136 expect(create.serverless.utils.fileExistsSync(path.join(tmpDir, 'event.json')))137 .to.be.equal(true);138 expect(create.serverless.utils.fileExistsSync(path.join(tmpDir, 'build.gradle')))139 .to.be.equal(true);140 expect(create.serverless.utils.fileExistsSync(path.join(tmpDir, 'gradlew')))141 .to.be.equal(true);142 expect(create.serverless.utils.fileExistsSync(path.join(tmpDir, 'gradlew.bat')))143 .to.be.equal(true);144 expect(create.serverless.utils.fileExistsSync(path.join(tmpDir, 'gradle', 'wrapper',145 'gradle-wrapper.jar')))146 .to.be.equal(true);147 expect(create.serverless.utils.fileExistsSync(path.join(tmpDir, 'gradle', 'wrapper',148 'gradle-wrapper.properties')))149 .to.be.equal(true);150 expect(create.serverless.utils.fileExistsSync(path.join(tmpDir, 'src', 'main', 'java',151 'hello', 'Handler.java'152 )))153 .to.be.equal(true);154 expect(create.serverless.utils.fileExistsSync(path.join(tmpDir, 'src', 'main', 'java',155 'hello', 'Request.java'156 )))157 .to.be.equal(true);158 expect(create.serverless.utils.fileExistsSync(path.join(tmpDir, 'src', 'main', 'java',159 'hello', 'Response.java'160 )))161 .to.be.equal(true);162 expect(create.serverless.utils.fileExistsSync(path.join(tmpDir, '.gitignore')))163 .to.be.equal(true);164 process.chdir(cwd);165 });166 });167 it('should generate scaffolding for "aws-scala-sbt" template', () => {168 const cwd = process.cwd();169 fse.mkdirsSync(tmpDir);170 process.chdir(tmpDir);171 create.options.template = 'aws-scala-sbt';172 return create.create().then(() => {173 expect(create.serverless.utils.fileExistsSync(path.join(tmpDir, 'serverless.yml')))174 .to.be.equal(true);175 expect(create.serverless.utils.fileExistsSync(path.join(tmpDir, 'event.json')))176 .to.be.equal(true);177 expect(create.serverless.utils.fileExistsSync(path.join(tmpDir, 'build.sbt')))178 .to.be.equal(true);179 expect(create.serverless.utils.fileExistsSync(path.join(tmpDir, 'src', 'main', 'scala',180 'hello', 'Handler.scala'181 )))182 .to.be.equal(true);183 expect(create.serverless.utils.fileExistsSync(path.join(tmpDir, 'src', 'main', 'scala',184 'hello', 'Request.scala'185 )))186 .to.be.equal(true);187 expect(create.serverless.utils.fileExistsSync(path.join(tmpDir, 'src', 'main', 'scala',188 'hello', 'Response.scala'189 )))190 .to.be.equal(true);191 expect(create.serverless.utils.fileExistsSync(path.join(tmpDir, '.gitignore')))192 .to.be.equal(true);193 process.chdir(cwd);194 });195 });196 // this test should live here because of process.cwd() which might cause trouble when using197 // nested dirs like its done here198 it('should create a plugin in the current directory', () => {199 const cwd = process.cwd();200 fse.mkdirsSync(tmpDir);201 process.chdir(tmpDir);202 // using the nodejs template (this test is completely be independent from the template)203 create.options.template = 'plugin';204 return create.create().then(() => {205 const serviceDir = tmpDir;206 // check if files are created in the correct directory207 expect(create.serverless.utils.fileExistsSync(208 path.join(serviceDir, 'index.js'))).to.be.equal(true);209 process.chdir(cwd);210 });211 });212 // this test should live here because of process.cwd() which might cause trouble when using213 // nested dirs like its done here214 it('should create a renamed service in the directory if using the "path" option', () => {215 const cwd = process.cwd();216 fse.mkdirsSync(tmpDir);217 process.chdir(tmpDir);218 create.options.path = 'my-new-service';219 create.options.name = null;220 // using the nodejs template (this test is completely be independent from the template)221 create.options.template = 'aws-nodejs';222 return create.create().then(() => {223 const serviceDir = path.join(tmpDir, create.options.path);224 // check if files are created in the correct directory225 expect(create.serverless.utils.fileExistsSync(226 path.join(serviceDir, 'serverless.yml'))).to.be.equal(true);227 expect(create.serverless.utils.fileExistsSync(228 path.join(serviceDir, 'handler.js'))).to.be.equal(true);229 // check if the service was renamed230 const serverlessYmlfileContent = fse231 .readFileSync(path.join(serviceDir, 'serverless.yml')).toString();232 expect((/service: my-new-service/).test(serverlessYmlfileContent)).to.equal(true);233 process.chdir(cwd);234 });235 });236 it('should create a custom renamed service in the directory if using ' +237 'the "path" and "name" option', () => {238 const cwd = process.cwd();239 fse.mkdirsSync(tmpDir);240 process.chdir(tmpDir);241 create.options.path = 'my-new-service';242 create.options.name = 'my-custom-new-service';243 // using the nodejs template (this test is completely be independent from the template)244 create.options.template = 'aws-nodejs';245 return create.create().then(() => {246 const serviceDir = path.join(tmpDir, create.options.path);247 // check if files are created in the correct directory248 expect(create.serverless.utils.fileExistsSync(249 path.join(serviceDir, 'serverless.yml'))).to.be.equal(true);250 expect(create.serverless.utils.fileExistsSync(251 path.join(serviceDir, 'handler.js'))).to.be.equal(true);252 // check if the service was renamed253 const serverlessYmlfileContent = fse254 .readFileSync(path.join(serviceDir, 'serverless.yml')).toString();255 expect((/service: my-custom-new-service/).test(serverlessYmlfileContent)).to.equal(true);256 process.chdir(cwd);257 });258 });259 });...

Full Screen

Full Screen

build-tools.js

Source:build-tools.js Github

copy

Full Screen

...42 43 try { fs.unlinkSync( new_file ); }44 catch (e) {;}45 46 if (!fileExistsSync( path.dirname(new_file) )) {47 mkdirp.sync( path.dirname(new_file) );48 }49 50 // fs.symlink takes a STRING (not a file path per se) as the old (existing) file, 51 // and it needs to be relative from new_file. So we need to resolve some things.52 var sym_new = path.resolve( new_file );53 var sym_old = path.relative( path.dirname(sym_new), path.resolve(old_file) );54 55 fs.symlink( sym_old, sym_new, callback );56};57var copyFile = exports.copyFile = function copyFile( old_file, new_file, callback ) {58 // copy file59 if (new_file.match(/\/$/)) new_file += path.basename(old_file);60 console.log( "Copy: " + old_file + " --> " + new_file );61 62 try { fs.unlinkSync( new_file ); }63 catch (e) {;}64 65 if (!fileExistsSync( path.dirname(new_file) )) {66 mkdirp.sync( path.dirname(new_file) );67 }68 69 var inp = fs.createReadStream(old_file);70 var outp = fs.createWriteStream(new_file);71 inp.on('end', callback );72 inp.pipe( outp );73};74var copyFiles = exports.copyFiles = function copyFiles( src_spec, dest_dir, callback ) {75 // copy multiple files to destination directory using filesystem globbing76 dest_dir = dest_dir.replace(/\/$/, '');77 78 glob(src_spec, {}, function (err, files) {79 // got files80 if (files && files.length) {81 async.eachSeries( files, function(src_file, callback) {82 // foreach file83 var stats = fileStatSync(src_file);84 if (stats && stats.isFile()) {85 copyFile( src_file, dest_dir + '/', callback );86 }87 else callback();88 }, callback );89 } // got files90 else {91 callback( err || new Error("No files found matching: " + src_spec) );92 }93 } );94};95var compressFile = exports.compressFile = function compressFile( src_file, gz_file, callback ) {96 // gzip compress file97 console.log( "Compress: " + src_file + " --> " + gz_file );98 99 if (fileExistsSync(gz_file)) {100 fs.unlinkSync( gz_file );101 }102 103 var gzip = zlib.createGzip();104 var inp = fs.createReadStream( src_file );105 var outp = fs.createWriteStream( gz_file );106 inp.on('end', callback );107 inp.pipe(gzip).pipe(outp);108};109var copyCompress = exports.copyCompress = function copyCompress( old_file, new_file, callback ) {110 // copy file and create gzip version as well111 if (new_file.match(/\/$/)) new_file += path.basename(old_file);112 113 copyFile( old_file, new_file, function(err) {114 if (err) return callback(err);115 116 // Make a compressed copy, so node-static will serve it up to browsers117 compressFile( old_file, new_file + '.gz', callback );118 } );119};120var symlinkCompress = exports.symlinkCompress = function symlinkCompress( old_file, new_file, callback ) {121 // symlink file and create gzip version as well122 if (new_file.match(/\/$/)) new_file += path.basename(old_file);123 124 symlinkFile( old_file, new_file, function(err) {125 if (err) return callback(err);126 127 // Make a compressed copy, so node-static will serve it up to browsers128 compressFile( old_file, new_file + '.gz', callback );129 } );130};131var deleteFile = exports.deleteFile = function deleteFile( file, callback ) {132 // delete file133 console.log( "Delete: " + file );134 135 if (fileExistsSync(file)) {136 fs.unlink( file, callback );137 }138 else callback();139};140var deleteFiles = exports.deleteFiles = function deleteFiles( spec, callback ) {141 // delete multiple files using filesystem globbing142 glob(spec, {}, function (err, files) {143 // got files144 if (files && files.length) {145 async.eachSeries( files, function(file, callback) {146 // foreach file147 deleteFile( file, callback );148 }, callback );149 } // got files150 else {151 callback( err );152 }153 } );154};155var chmodFiles = exports.chmodFiles = function chmodFiles( mode, spec, callback ) {156 // chmod multiple files to specified mode using filesystem globbing157 glob(spec, {}, function (err, files) {158 // got files159 if (files && files.length) {160 async.eachSeries( files, function(file, callback) {161 // foreach file162 fs.chmod( file, mode, callback );163 }, callback );164 } // got files165 else {166 callback( err || new Error("No files found matching: " + spec) );167 }168 } );169};170var copyDir = exports.copyDir = function copyDir( src_dir, dest_dir, exclusive, callback ) {171 // recursively copy dir and contents, optionally with exclusive mode172 // symlinks are followed, and the target is copied instead173 var src_spec = src_dir + '/*';174 175 // exclusive means skip if dest exists (do not replace)176 if (exclusive && fileExistsSync(dest_dir)) return callback();177 178 mkdirp.sync( dest_dir );179 180 glob(src_spec, {}, function (err, files) {181 // got files182 if (files && files.length) {183 async.eachSeries( files, function(src_file, callback) {184 // foreach file185 var stats = fs.statSync(src_file);186 187 if (stats.isFile()) {188 copyFile( src_file, dest_dir + '/', callback );189 }190 else if (stats.isDirectory()) {191 copyDir( src_file, dest_dir + '/' + path.basename(src_file), exclusive, callback );192 }193 }, callback );194 } // got files195 else {196 callback( err );197 }198 } );199};200var bundleCompress = exports.bundleCompress = function bundleCompress( args, callback ) {201 // compress bundle of files202 var html_file = args.html_file;203 var html_dir = path.dirname( html_file );204 205 if (!fileExistsSync( path.dirname(args.dest_bundle) )) {206 mkdirp.sync( path.dirname(args.dest_bundle) );207 }208 209 var raw_html = fs.readFileSync( html_file, 'utf8' );210 var regexp = new RegExp( "\\<\\!\\-\\-\\s+BUILD\\:\\s*"+args.match_key+"_START\\s*\\-\\-\\>([^]+)\\<\\!\\-\\-\\s*BUILD\\:\\s+"+args.match_key+"_END\\s*\\-\\-\\>" );211 212 if (raw_html.match(regexp)) {213 var files_raw = RegExp.$1;214 var files = [];215 216 files_raw.replace( /\b(src|href)\=[\"\']([^\"\']+)[\"\']/ig, function(m_all, m_g1, m_g2) {217 files.push( path.join(html_dir, m_g2) );218 } );219 220 if (files.length) {221 console.log("Bundling files: ", files);222 var raw_output = '';223 224 // optionally add file header225 if (args.header) {226 raw_output += args.header.trim() + "\n";227 }228 229 if (args.uglify) {230 console.log("Running UglifyJS...");231 var result = UglifyJS.minify( files );232 if (!result || !result.code) return callback( new Error("Failed to bundle script: Uglify failure") );233 raw_output += result.code;234 }235 else {236 for (var idx = 0, len = files.length; idx < len; idx++) {237 var file = files[idx];238 raw_output += fs.readFileSync( file, 'utf8' ) + "\n";239 }240 }241 242 // optionally strip source map links243 // /*# sourceMappingURL=materialdesignicons.min.css.map */244 if (args.strip_source_maps) {245 raw_output = raw_output.replace(/sourceMappingURL\=\S+/g, "");246 }247 248 // write out our bundle249 console.log(" --> " + args.dest_bundle);250 fs.writeFileSync(args.dest_bundle, raw_output);251 252 // swap a ref link into a copy of the HTML253 console.log(" --> " + html_file );254 raw_html = raw_html.replace( regexp, args.dest_bundle_tag );255 fs.writeFileSync(html_file, raw_html);256 257 // now make a compressed version of the bundle258 compressFile( args.dest_bundle, args.dest_bundle + '.gz', function(err) {259 if (err) return callback(err);260 261 // and compress the final HTML as well262 compressFile( html_file, html_file + '.gz', callback );263 });264 265 } // found files266 else {267 callback( new Error("Could not locate any file references: " + args.src_html + ": " + args.match_key) );268 }269 }270 else {271 callback( new Error("Could not locate match in HTML source: " + args.src_html + ": " + args.match_key) );272 }273};274var generateSecretKey = exports.generateSecretKey = function generateSecretKey( args, callback ) {275 // generate random secret key for a specified JSON config file276 // use regular expression to preserve natural file format277 var file = args.file;278 var key = args.key;279 var regex = new RegExp('(\\"'+Tools.escapeRegExp(key)+'\\"\\s*\\:\\s*\\")(.*?)(\\")');280 var secret_key = Tools.generateUniqueID(32);281 282 fs.readFile(file, 'utf8', function(err, text) {283 if (err) return callback(err);284 if (!text.match(regex)) return callback( new Error("Could not locate key to replace: " + file + ": " + key) );285 286 text = text.replace(regex, '$1' + secret_key + '$3');287 fs.writeFile( file, text, callback );288 });289};290var addToServerStartup = exports.addToServerStartup = function addToServerStartup( args, callback ) {291 // add service to init.d 292 // (RedHat and Ubuntu only -- do nothing on OS X)293 var src_file = args.src_file;294 var dest_dir = args.dest_dir;295 var service_name = args.service_name;296 var dest_file = dest_dir + '/' + service_name;297 298 // shell command that activates service on redhat or ubuntu299 var cmd = 'chkconfig '+service_name+' on || update-rc.d '+service_name+' defaults';300 301 // skip on os x, and if init dir is missing302 if (os.platform() == 'darwin') return callback();303 if (!fileExistsSync(dest_dir)) return callback( new Error("Cannot locate init.d directory: " + dest_dir) );304 if (process.getuid() != 0) return callback( new Error("Must be root to add services to server startup system.") );305 306 // copy file into place307 copyFile( src_file, dest_file, function(err) {308 if (err) return callback(err);309 310 // must be executable311 fs.chmod( dest_file, "775", function(err) {312 if (err) return callback(err);313 314 // exec shell command315 cp.exec( cmd, callback );316 } );317 } );...

Full Screen

Full Screen

http-server.js

Source:http-server.js Github

copy

Full Screen

...4const pull = require('pull-stream');5const debug = require('debug')('ssb:room:http');6const {parseAddress, parseMultiServerInvite} = require('ssb-ref');7const qr = require('qr-image');8function fileExistsSync(filename) {9 try {10 fs.accessSync(filename);11 } catch (err) {12 return false;13 }14 return true;15}16function startHTTPServer(ssb) {17 const app = express();18 app.use(express.static(__dirname + '/assets'));19 app.use(require('body-parser').urlencoded({extended: true}));20 app.set('port', 8007);21 app.set('views', __dirname + '/pages');22 app.set('view engine', 'ejs');23 const roomCfgFilePath = path.join(ssb.config.path, 'roomcfg');24 app.get('/', (req, res) => {25 if (!fileExistsSync(roomCfgFilePath)) {26 debug('There is no roomcfg file, ask for setup');27 res.redirect('setup');28 return;29 }30 fs.readFile(roomCfgFilePath, {encoding: 'utf-8'}, (err1, rawCfg) => {31 if (err1) debug('ERROR loading roomcfg file');32 const roomConfig = JSON.parse(rawCfg);33 let invite = ssb.invite.get();34 let host = parseAddress(parseMultiServerInvite(invite).remote).host;35 if (req.headers && req.headers.host) {36 const requestedHost = req.headers.host.split(':')[0];37 invite = invite.replace(host, requestedHost);38 host = requestedHost;39 }40 const qrCode = qr.svgObject(invite);41 pull(42 ssb.tunnel.endpoints(),43 pull.take(1),44 pull.drain(endpoints => {45 res.render('index', {46 host: host,47 name: roomConfig.name,48 description: roomConfig.description,49 onlineCount: (endpoints || {length: 0}).length,50 invite: invite,51 qrSize: qrCode.size,52 qrPath: qrCode.path,53 });54 }),55 );56 });57 });58 app.get('/setup', (req, res) => {59 if (fileExistsSync(roomCfgFilePath)) {60 res.redirect('/');61 return;62 }63 if (req.query && req.query.name) {64 fs.writeFileSync(roomCfgFilePath, JSON.stringify(req.query), {65 encoding: 'utf-8',66 });67 res.redirect('/');68 } else {69 res.render('setup');70 }71 });72 app.listen(app.get('port'), () => {73 debug('Express app is running on port %s', app.get('port'));...

Full Screen

Full Screen

start.js

Source:start.js Github

copy

Full Screen

...9const hjsonWrapper = {10 parse: (text) => hjson.parse(text, { keepWsc: true, }),11 stringify: (text) => hjson.stringify(text, { keepWsc: true, quotes: 'always', bracesSameLine: true }),12};13if (!fileExistsSync('config.hjson')) {14 fs.copySync('config.example.hjson', 'config.hjson');15}16nconf.file({ file: 'config.hjson', format: hjsonWrapper }).argv().env();17if (!nconf.get('tokenSecret')) {18 const random = crypto.randomBytes(256);19 nconf.set('tokenSecret', random.toString('hex'));20 nconf.save();21}22// Modules23const SocketServer = require('./socketserver/socketserver');24const path = require('path');25const webserver = require('./webserver/app');26const log = new(require('basic-logger'))({27 showTimestamp: true,28 prefix: 'SocketServer',29});30let server;31const webConfig = `// THIS IS AN AUTOMATICALLY GENERATED FILE\n\nvar config=JSON.parse('${JSON.stringify({32 useSSL: nconf.get('useSSL'),33 serverPort: nconf.get('socketServer:port'),34 selfHosted: !0,35 serverHost: nconf.get('socketServer:host')36})}')`;37if (nconf.get('hostWebserver')) {38 fs.writeFileSync(path.join(__dirname, '/webserver/public/lib/js', 'webconfig.js'), webConfig);39 server = (nconf.get('socketServer:port') === nconf.get('webServer:port') || nconf.get('socketServer:port') === '') ? webserver.server : null;40}41fs.writeFileSync(path.join(__dirname, '', 'webconfig.js'), webConfig);42const socketServer = new SocketServer(server);43process.on('uncaughtException', (err) => {44 console.log(err);45 console.log(err.stack);46 socketServer.gracefulExit();47});48process.on('exit', socketServer.gracefulExit);49process.on('SIGINT', socketServer.gracefulExit);50if (daemon == true) {51 if (fileExistsSync(`${__dirname}/pidfile`)) {52 try {53 const pid = fs.readFileSync(`${__dirname}/pidfile`, { encoding: 'utf-8' });54 process.kill(pid, 0);55 process.exit();56 } catch (e) {57 fs.unlinkSync(`${__dirname}/pidfile`);58 }59 }60 fs.writeFile(`${__dirname}/pidfile`, process.pid);61}62function fileExistsSync(path) {63 let exists = false;64 try {65 exists = fs.statSync(path);66 } catch (err) {67 exists = false;68 }69 return !!exists;...

Full Screen

Full Screen

mixinFile.js

Source:mixinFile.js Github

copy

Full Screen

1'use strict';2var fs = require('fs');3var mkdirp = require('mkdirp');4var path = require('path');5var stripJsonComments = require('strip-json-comments');6/**7 * Read a text file and return its content as a string8 * @param {String} filename The filename9 * @param {String} dirname The directory name (optional)10 * @returns {String} The file content as a string11 */12var readTextFile = function(filename, dirname) {13 // when dirname is null or undefined we read from local path, otherwise we read from absolute path14 if (dirname && !path.isAbsolute(filename)) {15 filename = path.resolve(path.join(dirname, filename));16 }17 var body = fs.readFileSync(filename, 'utf-8');18 return body;19};20/**21 * Read a json file and return its content as an object22 * @param {String} filename The filename23 * @param {String} dirname The directory name (optional)24 * @returns {Object} The file content as an object25 */26var readJsonFile = function(filename, dirname) {27 var body = readTextFile(filename, dirname);28 return JSON.parse(stripJsonComments(body));29};30/**31 * Create a folder synchronously32 * @param {String} path The path33 */34var createDirSync = function(path) {35 mkdirp.sync(path);36};37/**38 * Check if a file or path exists39 * @param {String} file - The file path40 * @returns {Boolean} - true if exists, false otherwise41 */42var fileExistsSync = function(file) {43 try {44 fs.accessSync(file);45 return true;46 } catch (e) {47 return false;48 }49};50module.exports = {51 extend: function(generator) {52 var mixins = generator.mixins = generator.mixins || {};53 mixins.readTextFile = readTextFile.bind(generator);54 mixins.readJsonFile = readJsonFile.bind(generator);55 mixins.createDirSync = createDirSync;56 mixins.fileExistsSync = fileExistsSync;57 }...

Full Screen

Full Screen

configuration.js

Source:configuration.js Github

copy

Full Screen

...5 webhooks: {'<Your webhook URL>': shared_secret_default_value}6};7var configFile = './conf/config.json';8var data;9if (fileExistsSync(configFile)) {10 try {11 data = fs.readFileSync(configFile)12 configuration = JSON.parse(data);13 }14 catch (err) {15 console.error('There has been an error parsing the config.json')16 console.error(err);17 }18}19else {20 data = JSON.stringify(configuration);21 fs.writeFile(configFile, data, function (err) {22 if (err) {23 console.log('There has been an error saving your configuration data.');24 console.log(err.message);25 return;26 }27 console.log('Configuration saved successfully.')28 });29}30function fileExistsSync(file) {31 try {32 fs.accessSync(file, fs.constants.R_OK | fs.constants.W_OK);33 return true;34 } catch (err) {35 return false;36 }37}38function getConfiguration() {39 return configuration;40}41function getSharedSecretForWebhook(webhookUrl) {42 assert.ok(getConfiguration().webhooks.hasOwnProperty(webhookUrl), "No shared_secret defined for for webhook url: " + webhookUrl);43 assert.notStrictEqual(getConfiguration().webhooks[webhookUrl], "", "No shared_secret defined for for webhook url: " + webhookUrl);44 assert.notStrictEqual(getConfiguration().webhooks[webhookUrl], shared_secret_default_value, "No shared_secret defined for for webhook url: " + webhookUrl);...

Full Screen

Full Screen

fs.js

Source:fs.js Github

copy

Full Screen

...14 });15 });16}17exports.fileExists = fileExists;18function fileExistsSync(filepath) {19 return fs.existsSync(filepath);20}21exports.fileExistsSync = fileExistsSync;22/**23 * Read file by specified filepath;24 */25function readFile(filepath) {26 return new Promise((resolve, reject) => {27 fs.readFile(filepath, (err, data) => {28 if (err) {29 return reject(err);30 }31 resolve(data.toString());32 }); ...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1module.exports = {2 'Demo test Google' : function (browser) {3 .waitForElementVisible('body', 1000)4 .assert.title('Google')5 .assert.visible('input[type=text]')6 .setValue('input[type=text]', 'nightwatch')7 .waitForElementVisible('button[name=btnG]', 1000)8 .click('button[name=btnG]')9 .pause(1000)10 .assert.containsText('#main', 'Night Watch')11 .end();12 }13};14module.exports = {15 "selenium" : {

Full Screen

Using AI Code Generation

copy

Full Screen

1module.exports = {2 'Demo test Google' : function (browser) {3 .waitForElementVisible('body', 1000)4 .assert.title('Google')5 .assert.visible('input[type=text]')6 .setValue('input[type=text]', 'nightwatch')7 .waitForElementVisible('button[name=btnG]', 1000)8 .click('button[name=btnG]')9 .pause(1000)10 .assert.containsText('#main', 'Night Watch')11 .end();12 }13};14* **Miguel Angel Palencia** - *Initial work* - [miguelpalencia](

Full Screen

Using AI Code Generation

copy

Full Screen

1module.exports = {2 'Demo test Google' : function (browser) {3 .waitForElementVisible('body', 1000)4 .assert.title('Google')5 .assert.visible('input[type=text]')6 .setValue('input[type=text]', 'nightwatch')7 .waitForElementVisible('input[name=btnK]', 1000)8 .click('input[name=btnK]')9 .pause(1000)10 .assert.containsText('#main', 'Night Watch')11 .end();12 },13 'Demo test Yahoo' : function (browser) {14 .waitForElementVisible('body', 1000)15 .assert.title('Yahoo')16 .assert.visible('input[type=text]')17 .setValue('input[type=text]', 'nightwatch')18 .waitForElementVisible('input[name=btnK]', 1000)19 .click('input[name=btnK]')20 .pause(1000)21 .assert.containsText('#main', 'Night Watch')22 .end();23 }24};25{26 "selenium" : {27 "cli_args" : {28 }29 },30 "test_settings" : {31 "default" : {32 "screenshots" : {33 },34 "desiredCapabilities": {35 }36 }37 }38}39{40 "scripts": {

Full Screen

Using AI Code Generation

copy

Full Screen

1module.exports = {2 'Demo test Google' : function (browser) {3 .waitForElementVisible('body', 1000)4 .assert.title('Google')5 .assert.visible('input[type=text]')6 .setValue('input[type=text]', 'nightwatch')7 .waitForElementVisible('button[name=btnG]', 1000)8 .click('button[name=btnG]')9 .pause(1000)10 .assert.containsText('#main', 'Night Watch')11 .end();12 }13};14module.exports = {15 'Demo test Google' : function (browser) {16 .waitForElementVisible('body', 1000)17 .assert.title('Google')18 .assert.visible('input[type=text]')19 .setValue('input[type=text]', 'nightwatch')20 .waitForElementVisible('button[name=btnG]', 1000)21 .click('button[name=btnG]')22 .pause(1000)23 .assert.containsText('#main', 'Night Watch')24 .end();25 }26};27module.exports = {28 'Demo test Google' : function (browser) {29 .waitForElementVisible('body', 1000)30 .assert.title('Google')31 .assert.visible('input[type=text]')32 .setValue('input[type=text]', 'nightwatch')33 .waitForElementVisible('button[name=btnG]', 1000)34 .click('button[name=btnG]')35 .pause(1000)36 .assert.containsText('#main', 'Night Watch')37 .end();38 }39};40module.exports = {41 'Demo test Google' : function (browser) {42 .waitForElementVisible('body', 1000)43 .assert.title('Google')44 .assert.visible('input[type=text]')45 .setValue('input[type=text]', 'nightwatch')46 .waitForElementVisible('button[name=btnG]', 1000)47 .click('button[name=btnG]')

Full Screen

Using AI Code Generation

copy

Full Screen

1module.exports = {2 'Test Example' : function (browser) {3 .pause(1000)4 .assert.fileExistsSync('test.js')5 .end();6 }7};8module.exports = {9 'Test Example' : function (browser) {10 .pause(1000)11 .waitForFileExistsSync('test.js', 5000)12 .end();13 }14};

Full Screen

Using AI Code Generation

copy

Full Screen

1module.exports = {2 'Test Case' : function (browser) {3 .pause(1000)4 .assert.fileExistsSync('/home/nightwatch/nightwatch-0.9.16/nightwatch.json')5 .end();6 }7};8{9 "selenium" : {

Full Screen

Using AI Code Generation

copy

Full Screen

1module.exports = {2 'Test if file exists': function (browser) {3 browser.fileExistsSync('test.js')4 }5}6module.exports = {7 'Test if file exists': function (browser) {8 browser.fileExistsAsync('test.js')9 }10}11module.exports = {12 'Test if file exists': function (browser) {13 browser.fileDeleteSync('test.js')14 }15}16module.exports = {17 'Test if file exists': function (browser) {18 browser.fileDeleteAsync('test.js')19 }20}21module.exports = {22 'Test if file exists': function (browser) {23 browser.fileCreateFolderSync('testFolder')24 }25}26module.exports = {27 'Test if file exists': function (browser) {28 browser.fileCreateFolderAsync('testFolder')29 }30}31module.exports = {32 'Test if file exists': function (browser) {33 browser.fileDeleteFolderSync('

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Nightwatch automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful