當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript tmp.fileSync函數代碼示例

本文整理匯總了TypeScript中tmp.fileSync函數的典型用法代碼示例。如果您正苦於以下問題:TypeScript fileSync函數的具體用法?TypeScript fileSync怎麽用?TypeScript fileSync使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了fileSync函數的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: _setupServerOptions

 function _setupServerOptions() {
   _keyFile = tmp.fileSync();
   _certFile = tmp.fileSync();
   _serverOptions = {
     root,
     protocol: 'h2',
     keyPath: _keyFile.name,
     certPath: _certFile.name
   };
 }
開發者ID:tony19-contrib,項目名稱:polyserve,代碼行數:10,代碼來源:start_server_test.ts

示例2: createDatabaseSuite

export function createDatabaseSuite(suiteName: string, suite: DatabaseTestSuite) {
  const sqlitePath = tmp.fileSync().name
  const sqlite = new Database(logger.T)
  const postgres = new Database(logger.T)

  describe(`DB[SQLite] ${suiteName}`, async () => {
    beforeAll(async () => {
      await sqlite.initialize({
        location: sqlitePath,
        type: 'sqlite'
      })

      await sqlite.bootstrap()
      await sqlite.seedForTests()
    })

    afterAll(async () => {
      await sqlite.teardownTables()
      await sqlite.knex.destroy()
    })

    afterEach(async () => {
      await sqlite.teardownTables()
      await sqlite.bootstrap()
      await sqlite.seedForTests()
    })

    await suite(sqlite)
  })

  describe(`DB[Postgres] ${suiteName}`, () => {
    beforeAll(async () => {
      await postgres.initialize({
        type: 'postgres',
        host: process.env.PG_HOST || 'localhost',
        port: Number(process.env.PG_PORT || 5432),
        database: process.env.PG_DB || TEST_DATABASE,
        user: process.env.PG_USER || 'postgres',
        password: process.env.PG_PASSWORD || ''
      })

      await postgres.bootstrap()
      await postgres.seedForTests()
    })

    afterAll(async () => {
      await postgres.teardownTables()
      await postgres.knex.destroy()
    })

    afterEach(async () => {
      await postgres.teardownTables()
      await postgres.bootstrap()
      await postgres.seedForTests()
    })

    suite(postgres)
  })
}
開發者ID:seffalabdelaziz,項目名稱:botpress,代碼行數:59,代碼來源:index.tests.ts

示例3: it

  it("should connect securely", async () => {
    const attrs = [{ name: "commonName", value: "buttplugtest.com" }];
    const pems = selfsigned.generate(attrs, { days: 365 });
    const tmpcert = tmp.fileSync();
    const tmpprivate = tmp.fileSync();
    fs.writeFileSync(tmpcert.name, pems.cert);
    fs.writeFileSync(tmpprivate.name, pems.private);
    _server.StartSecureServer(tmpcert.name, tmpprivate.name, _port, "127.0.0.1");

    const bpc = new ButtplugClient("test");
    await bpc.Connect(_secureConnector);
    expect(bpc.Connected).toBe(true);
    await bpc.Disconnect();
    expect(bpc.Connected).toBe(false);
    tmpcert.removeCallback();
    tmpprivate.removeCallback();
  });
開發者ID:metafetish,項目名稱:buttplug-js,代碼行數:17,代碼來源:test-websockets.ts

示例4: createArchive

async function createArchive(ref: string): Promise<any> {
  const tar = spawn('git', ['archive', '--format', 'tar.gz', ref])
  const file = tmp.fileSync({postfix: '.tar.gz'})
  const write = tar.stdout.pipe(fs.createWriteStream(file.name))

  return new Promise((resolve, reject) => {
    write.on('close', () => resolve(file.name))
    write.on('error', reject)
  })
}
開發者ID:jimmyurl,項目名稱:cli,代碼行數:10,代碼來源:git.ts

示例5: makeArchive

function makeArchive(app: string, includeDotfiles: boolean) {
  // create a file to stream archive data to.
  const { name: tarPath } = tmp.fileSync({
    discardDescriptor: true,
    prefix: `${app}-deploy-`,
    postfix: '.tar.gz'
  });
  const output = fs.createWriteStream(tarPath);
  const archive = archiver('tar', {
    gzip: true
  });

  // listen for all archive data to be written
  output.on('close', () => {
    // print something?
  });

  // good practice to catch warnings (ie stat failures and other non-blocking errors)
  archive.on('warning', (err) => {
    if (err.code === 'ENOENT') {
      // log warning
    } else {
      // throw error
      throw err;
    }
  });

  // good practice to catch this error explicitly
  archive.on('error', (err) => {
    throw err;
  });

  // pipe archive data to the file
  archive.pipe(output);

  return globby('**', {
    dot: includeDotfiles,
    gitignore: true,
    gitignoreName: '.skyignore'
  })
    .then((paths: [string]) => {
      paths.forEach((path) => {
        archive.file(path, {
          name: path
        });
      });
      // finalize the archive (ie we are done appending files but streams have to finish yet)
      return archive.finalize();
    })
    .then(() => {
      return tarPath;
    });
}
開發者ID:SkygearIO,項目名稱:skycli,代碼行數:53,代碼來源:deploy.ts

示例6: Promise

 return new Promise((resolve, reject) => {
   const tmpfile = tmp.fileSync();
   const req = request.get(remoteUrl);
   const writeStream = fs.createWriteStream(tmpfile.name);
   req.on("error", (err: any) => reject(err));
   req.on("response", (response) => {
     if (response.statusCode !== 200) {
       reject(new FirebaseError(`download failed, status ${response.statusCode}`, { exit: 1 }));
     }
   });
   writeStream.on("finish", () => {
     resolve(tmpfile.name);
   });
   req.pipe(writeStream);
 });
開發者ID:firebase,項目名稱:firebase-tools,代碼行數:15,代碼來源:download.ts

示例7: initConcatJs

/**
 * Entry-point for the Karma plugin.
 */
function initConcatJs(logger, emitter, basePath) {
  const log = logger.create('framework.concat_js');

  // Create a tmp file for the concat bundle that is automatically cleaned up on
  // exit.
  const tmpFile = tmp.fileSync({keep: false, dir: process.env['TEST_TMPDIR']});

  emitter.on('file_list_modified', files => {
    const bundleFile = {
      path: '/concatjs_bundle.js',
      contentPath: tmpFile.name,
      isUrl: false,
      content: ''
    } as any;
    const included = [];

    files.included.forEach(file => {
      if (path.extname(file.originalPath) !== '.js') {
        // Preserve all non-JS that were there in the included list.
        included.push(file);
      } else {
        const relativePath =
            path.relative(basePath, file.originalPath).replace(/\\/g, '/');

        // Remove 'use strict'.
        let content = file.content.replace(/('use strict'|"use strict");?/,
                                           '');
        content = JSON.stringify(
            content + '\n//# sourceURL=http://concatjs/base/' +
            relativePath + '\n');
        content = `//${relativePath}\neval(${content});\n`;
        bundleFile.content += content;
      }
    });

    bundleFile.sha = sha1(new Buffer(bundleFile.content));
    bundleFile.mtime = new Date();
    included.unshift(bundleFile);

    files.included = included;
    files.served.push(bundleFile);

    log.debug('Writing concatjs bundle to tmp file %s',
        bundleFile.contentPath);
    fs.writeFileSync(bundleFile.contentPath, bundleFile.content);
  });
}
開發者ID:ramyothman,項目名稱:testdashboard,代碼行數:50,代碼來源:index.ts

示例8: request

    store: (absoluteImagePath: string): Thenable<string> => {
        if (ImageCache.has(absoluteImagePath)) {
            return ImageCache.get(absoluteImagePath);
        } else {
            try {
                const absoluteImageUrl = url.parse(absoluteImagePath);
                const tempFile = tmp.fileSync({
                    postfix: absoluteImageUrl.pathname ? path.parse(absoluteImageUrl.pathname).ext : 'png'
                });
                const filePath = tempFile.name;
                const promise = new Promise<string>((resolve, reject) => {
                    if (absoluteImageUrl.protocol && absoluteImageUrl.protocol.startsWith('http')) {
                        var r = request(absoluteImagePath);
                        r.on('error', function(err) {
                            reject(err);
                        });
                        r.on('response', function(res) {
                            r.pipe(fs.createWriteStream(filePath)).on('close', () => {
                                resolve(filePath);
                            });
                        });
                    } else {
                        try {
                            const handle = fs.watch(absoluteImagePath, function fileChangeListener() {
                                handle.close();
                                fs.unlink(filePath, () => {});
                                ImageCache.delete(absoluteImagePath);
                            });
                        } catch (e) {}
                        copyFile(absoluteImagePath, filePath, err => {
                            if (!err) {
                                resolve(filePath);
                            }
                        });
                    }
                });
                ImageCache.set(absoluteImagePath, promise);

                return promise;
            } catch (error) {}
        }
    },
開發者ID:kisstkondoros,項目名稱:gutter-preview,代碼行數:42,代碼來源:imagecache.ts

示例9: processFile

async function processFile(filename: string) {
    let tmpFile = tmp.fileSync();
    let destFileName = getDestFileName(filename);

    console.log(`Parsing file ${filename} to ${destFileName}`);

    try {
        let parsed = sass.renderSync({ file: filename, outFile: tmpFile.name });
        let css = (new Buffer(parsed.css)).toString();
        fs.writeFileSync(tmpFile.name, css);
        let cssToDtsConverter = new DtsCreator();
        let content = await cssToDtsConverter.create(tmpFile.name);
        let tokens = content.rawTokenList as string[];

        let typings = TsTypeInfo.createFile();
        let formatter = (token) => program['camelCase'] ? camelCase(token) : token;

        typings.addClasses({
            name: 'Styles',
            isExported: true,
            isDefaultExportOfFile: true,
            isAmbient: true,
            isNamedExportOfFile: true,
            hasDeclareKeyword: true,
            properties: tokens.map<TsTypeInfo.ClassPropertyStructure>(token => ({ name: `'${formatter(token)}'`, type: 'string' })),
            onAfterWrite: writer => {
                writer.writeLine(``);                                
                writer.writeLine(`declare var style: Styles`);
                writer.writeLine(`export = style;`);
            }
        });

        fs.writeFileSync(destFileName, typings.write());
    }
    catch (e) {
        console.error(e);
        throw e;
    }
    finally {
        tmpFile.removeCallback();
    }
}
開發者ID:Bolisov,項目名稱:sass-css-modules-to-typings-converter,代碼行數:42,代碼來源:index.ts

示例10: convertToTsv

function convertToTsv(filename: string, options: IXLSXExtractOptions, cb: (err: Error | null, tsv?: string) => void) {
	const file = tmp.fileSync();
	fs.unlinkSync(file.name);
	let error: Error | null = null;
	new XLSX().convert(filename, file.name, options)
		.on('end', () => {
			const exists = fs.existsSync(file.name);
			assert.equal(exists, true, 'file not written');
			if (exists) {
				const tsv = fs.readFileSync(file.name).toString();
				file.removeCallback();
				cb(error, tsv);
			} else {
				cb(error);
			}

		})
		.on('error', err => {
			error = err;
		});
}
開發者ID:ffalt,項目名稱:xlsx-extract,代碼行數:21,代碼來源:test.ts


注:本文中的tmp.fileSync函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。