fs#appendFileSync JavaScript Examples

The following examples show how to use fs#appendFileSync. 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: outbox-store.js    From medusa with MIT License 6 votes vote down vote up
appendToBuffer(event) {
    try {
      appendFileSync(this.bufferFilePath, event, `utf8`)
    } catch (e) {
      if (isTruthy(MEDUSA_TELEMETRY_VERBOSE)) {
        console.error("Failed to append to buffer", e)
      }
    }
  }
Example #2
Source File: index.js    From playwright-addons with MIT License 5 votes vote down vote up
/**
 * Enable the stealth add-on
 * @param {Browser} br - Playwright Browser or BrowserContext object
 */
export default async function (br) {
    if (typeof br !== 'object' || !(br.contexts || br.pages)) {
        console.error('Need to provide a Playwright Browser or BrowserContext object');
    } else {
        let context = br.contexts ? br.contexts() : [br];

        await context.forEach(async c => {
            // Init evasions script on every page load
            await c.addInitScript({ path: dirname(fileURLToPath(import.meta.url)) + '/evasions.js' });

            // Properly set UA info (vanilla Playwright only sets the UA)
            const userAgent = c._options.userAgent || '';
            const acceptLanguage = c._options.locale;
            const platform = userAgent.indexOf('Macintosh') !== -1 ? 'MacIntel' : (userAgent.indexOf('Windows') !== -1 ? 'Win32' : '');
            const oscpu = userAgent.match('(Intel.*?|Windows.*?)[;)]') ? userAgent.match('(Intel.*?|Windows.*?)[;)]')[1] : '';
            const userAgentMetadata = undefined; // TODO, see https://chromedevtools.github.io/devtools-protocol/tot/Emulation/#type-UserAgentMetadata

            // Firefox - write to prefs
            if (br.constructor.name.indexOf('FFBrowser') === 0) {
                let prefs = `
                user_pref("general.appversion.override", "` + userAgent.replace('Mozilla/', '') + `");
                user_pref("general.oscpu.override", "` + oscpu + `");
                user_pref("general.platform.override", "` + platform + `");
                user_pref("general.useragent.override", "` + userAgent + `");
                `;
                if (acceptLanguage) {
                    prefs += `
                    user_pref("general.useragent.locale", "` + acceptLanguage + `");
                    user_pref("intl.accept_languages", "` + acceptLanguage + `");
                    `;
                }
                let proc = (br._options.ownedServer ? br._options.ownedServer : br._browser._options.ownedServer)._process;
                proc.spawnargs.forEach((a, k) => {
                    if (a.indexOf('-profile') !== -1) {
                        let dir = proc.spawnargs[k + 1];
                        appendFileSync(dir + '/prefs.js', prefs);
                    }
                });
            } else { // Chromium - use CDP to override
                c.pages().forEach(async p => {
                    try {
                        (await p.context().newCDPSession(p)).send('Emulation.setUserAgentOverride', { userAgent, acceptLanguage, platform, userAgentMetadata })
                    } catch (e) { console.log('Warning: could not set UA override:', e); }
                });

                c.on('page', async p => {
                    try {
                        (await p.context().newCDPSession(p)).send('Emulation.setUserAgentOverride', { userAgent, acceptLanguage, platform, userAgentMetadata })
                    } catch (e) { console.log('Warning: could not set UA override:', e); }
                });

            }
        });

        console.log('Stealth enabled');
    }
}
Example #3
Source File: index.js    From kit with MIT License 5 votes vote down vote up
/** @type {import('.').default} */
export default function ({ split = false, edge = edge_set_in_env_var } = {}) {
	return {
		name: '@sveltejs/adapter-netlify',

		async adapt(builder) {
			const netlify_config = get_netlify_config();

			// "build" is the default publish directory when Netlify detects SvelteKit
			const publish = get_publish_directory(netlify_config, builder) || 'build';

			// empty out existing build directories
			builder.rimraf('.netlify/edge-functions');
			builder.rimraf('.netlify/functions-internal');
			builder.rimraf('.netlify/server');
			builder.rimraf('.netlify/package.json');
			builder.rimraf('.netlify/serverless.js');

			builder.log.minor(`Publishing to "${publish}"`);

			builder.log.minor('Copying assets...');
			builder.writeStatic(publish);
			builder.writeClient(publish);
			builder.writePrerendered(publish);

			builder.log.minor('Writing custom headers...');
			const headers_file = join(publish, '_headers');
			builder.copy('_headers', headers_file);
			appendFileSync(
				headers_file,
				`\n\n/${builder.config.kit.appDir}/immutable/*\n  cache-control: public\n  cache-control: immutable\n  cache-control: max-age=31536000\n`
			);

			// for esbuild, use ESM
			// for zip-it-and-ship-it, use CJS until https://github.com/netlify/zip-it-and-ship-it/issues/750
			const esm = netlify_config?.functions?.node_bundler === 'esbuild';

			if (edge) {
				if (split) {
					throw new Error('Cannot use `split: true` alongside `edge: true`');
				}

				await generate_edge_functions({ builder });
			} else {
				await generate_lambda_functions({ builder, esm, split, publish });
			}
		}
	};
}
Example #4
Source File: index.js    From kit with MIT License 4 votes vote down vote up
/**
 * @param { object } params
 * @param {import('@sveltejs/kit').Builder} params.builder
 * @param { string } params.publish
 * @param { boolean } params.split
 * @param { boolean } params.esm
 */
async function generate_lambda_functions({ builder, publish, split, esm }) {
	builder.mkdirp('.netlify/functions-internal');

	/** @type {string[]} */
	const redirects = [];
	builder.writeServer('.netlify/server');

	const replace = {
		'0SERVER': './server/index.js' // digit prefix prevents CJS build from using this as a variable name, which would also get replaced
	};
	if (esm) {
		builder.copy(`${files}/esm`, '.netlify', { replace });
	} else {
		glob('**/*.js', { cwd: '.netlify/server' }).forEach((file) => {
			const filepath = `.netlify/server/${file}`;
			const input = readFileSync(filepath, 'utf8');
			const output = esbuild.transformSync(input, { format: 'cjs', target: 'node12' }).code;
			writeFileSync(filepath, output);
		});

		builder.copy(`${files}/cjs`, '.netlify', { replace });
		writeFileSync(join('.netlify', 'package.json'), JSON.stringify({ type: 'commonjs' }));
	}

	if (split) {
		builder.log.minor('Generating serverless functions...');

		await builder.createEntries((route) => {
			const parts = [];
			// Netlify's syntax uses '*' and ':param' as "splats" and "placeholders"
			// https://docs.netlify.com/routing/redirects/redirect-options/#splats
			for (const segment of route.segments) {
				if (segment.rest) {
					parts.push('*');
					break; // Netlify redirects don't allow anything after a *
				} else if (segment.dynamic) {
					parts.push(`:${parts.length}`);
				} else {
					parts.push(segment.content);
				}
			}

			const pattern = `/${parts.join('/')}`;
			const name = parts.join('-').replace(/[:.]/g, '_').replace('*', '__rest') || 'index';

			return {
				id: pattern,
				filter: (other) => matches(route.segments, other.segments),
				complete: (entry) => {
					const manifest = entry.generateManifest({
						relativePath: '../server',
						format: esm ? 'esm' : 'cjs'
					});

					const fn = esm
						? `import { init } from '../serverless.js';\n\nexport const handler = init(${manifest});\n`
						: `const { init } = require('../serverless.js');\n\nexports.handler = init(${manifest});\n`;

					writeFileSync(`.netlify/functions-internal/${name}.js`, fn);

					redirects.push(`${pattern} /.netlify/functions/${name} 200`);
					redirects.push(`${pattern}/__data.json /.netlify/functions/${name} 200`);
				}
			};
		});
	} else {
		builder.log.minor('Generating serverless functions...');

		const manifest = builder.generateManifest({
			relativePath: '../server',
			format: esm ? 'esm' : 'cjs'
		});

		const fn = esm
			? `import { init } from '../serverless.js';\n\nexport const handler = init(${manifest});\n`
			: `const { init } = require('../serverless.js');\n\nexports.handler = init(${manifest});\n`;

		writeFileSync('.netlify/functions-internal/render.js', fn);
		redirects.push('* /.netlify/functions/render 200');
	}

	// this should happen at the end, after builder.writeStatic(...),
	// so that generated redirects are appended to custom redirects
	// rather than replaced by them
	builder.log.minor('Writing redirects...');
	const redirect_file = join(publish, '_redirects');
	if (existsSync('_redirects')) {
		builder.copy('_redirects', redirect_file);
	}
	builder.mkdirp(dirname(redirect_file));
	appendFileSync(redirect_file, `\n\n${redirects.join('\n')}`);
}