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


TypeScript fs.readdirSync函數代碼示例

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


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

示例1:

 getDirectories: (dir) => fs.readdirSync(dir),
開發者ID:erikkemperman,項目名稱:tslint,代碼行數:1,代碼來源:test.ts

示例2: readdirSync

 .then(() => oldNumberOfFiles = readdirSync('dist').length)
開發者ID:JasonGoemaat,項目名稱:angular-cli,代碼行數:1,代碼來源:lazy-module.ts

示例3: getFiles

export function getFiles(srcpath: string): string[] {
    return fs.readdirSync(srcpath).filter(function (file: string) {
        return fs.statSync(path.join(srcpath, file)).isFile();
    });
}
開發者ID:TNOCS,項目名稱:csWeb,代碼行數:5,代碼來源:Utils.ts

示例4: start

export default function start(serverDataPath: string) {
  dataPath = serverDataPath;
  SupCore.log(`Using data from ${dataPath}.`);
  process.on("uncaughtException", onUncaughtException);

  loadConfig();

  const { version, superpowers: { appApiVersion: appApiVersion } } = JSON.parse(fs.readFileSync(`${__dirname}/../package.json`, { encoding: "utf8" }));
  SupCore.log(`Server v${version} starting...`);
  fs.writeFileSync(`${__dirname}/../public/superpowers.json`, JSON.stringify({ version, appApiVersion, hasPassword: config.server.password.length !== 0 }, null, 2));

  // SupCore
  (global as any).SupCore = SupCore;
  SupCore.systemsPath = path.join(dataPath, "systems");

  // List available languages
  languageIds = fs.readdirSync(`${__dirname}/../public/locales`);
  languageIds.unshift("none");

  // Main HTTP server
  mainApp = express();

  mainApp.use(cookieParser());
  mainApp.use(handleLanguage);

  mainApp.get("/", (req, res) => { res.redirect("/hub"); });
  mainApp.get("/login", serveLoginIndex);
  mainApp.get("/hub", enforceAuth, serveHubIndex);
  mainApp.get("/project", enforceAuth, serveProjectIndex);

  mainApp.use("/projects/:projectId/*", serveProjectWildcard);
  mainApp.use("/", express.static(`${__dirname}/../public`));

  mainHttpServer = http.createServer(mainApp);
  mainHttpServer.on("error", onHttpServerError.bind(null, config.server.mainPort));

  io = socketio(mainHttpServer, { transports: [ "websocket" ] });

  // Build HTTP server
  buildApp = express();

  buildApp.get("/", redirectToHub);
  buildApp.get("/systems/:systemId/SupCore.js", serveSystemSupCore);

  buildApp.use("/", express.static(`${__dirname}/../public`));

  buildApp.get("/builds/:projectId/:buildId/*", (req, res) => {
    const projectServer = hub.serversById[req.params.projectId];
    if (projectServer == null) { res.status(404).end("No such project"); return; }
    let buildId = req.params.buildId as string;
    if (buildId === "latest") buildId = (projectServer.nextBuildId - 1).toString();
    res.sendFile(path.join(projectServer.buildsPath, buildId, req.params[0]));
  });

  buildHttpServer = http.createServer(buildApp);
  buildHttpServer.on("error", onHttpServerError.bind(null, config.server.buildPort));

  loadSystems(mainApp, buildApp, onSystemsLoaded);

  // Save on exit and handle crashes
  process.on("SIGINT", onExit);
  process.on("message", (msg: string) => { if (msg === "stop") onExit(); });
}
開發者ID:alphafork,項目名稱:Game-Engine-superpowers-core,代碼行數:63,代碼來源:start.ts

示例5: mapLines

const createDTS = () => {
  const header = `//
// Autogenerated from scripts/danger-dts.ts
//

import * as GitHub from "github"

declare module "danger" {
`
  const footer = `}
`

  let fileOutput = ""

  const extras = ["source/platforms/messaging/violation.ts"]
  const dslFiles = fs.readdirSync("source/dsl").map(f => `source/dsl/${f}`)

  dslFiles.concat(extras).forEach(file => {
    // Sometimes they have more stuff, in those cases
    // offer a way to crop the file.
    const content = fs.readFileSync(file).toString()
    if (content.includes("/// End of Danger DSL definition")) {
      fileOutput += content.split("/// End of Danger DSL definition")[0]
    } else {
      fileOutput += content
    }
    fileOutput += "\n"
  })

  // The definition of all the exposed vars is inside
  // the Dangerfile.js file.
  const allDangerfile = fs.readFileSync("source/runner/Dangerfile.ts").toString()
  const moduleContext = allDangerfile
    .split("/// Start of Danger DSL definition")[1]
    .split("/// End of Danger DSL definition")[0]

  // we need to add either `declare function` or `declare var` to the interface
  const context = mapLines(moduleContext, (line: string) => {
    if (line.length === 0 || line.includes("*")) {
      const newLine = line.trim()
      // Make sure TSLint passes
      if (newLine.startsWith("*")) {
        return " " + newLine
      }
      return newLine
    }
    if (line.includes("export type")) {
      return line
    }
    if (line.includes("(")) {
      return "function " + line.trim()
    }
    if (line.includes(":")) {
      return "const " + line.trim()
    }
    return ""
  })

  fileOutput += context

  // Remove all JS-y bits
  fileOutput = fileOutput
    .split("\n")
    .filter(line => {
      return !line.startsWith("import") && !line.includes("* @type ")
    })
    .join("\n")

  const trimmedWhitespaceLines = fileOutput.replace(/\n\s*\n\s*\n/g, "\n")
  const noRedundantExports = trimmedWhitespaceLines
    .replace(/export interface/g, "interface")
    .replace(/export type/g, "type")
  const indentedBody = mapLines(noRedundantExports, line => (line.length ? `  ${line}` : ""))
  return header + indentedBody + footer
}
開發者ID:tychota,項目名稱:danger-js,代碼行數:75,代碼來源:danger-dts.ts

示例6: getDirectories

 function getDirectories(path: string): string[] {
     return filter<string>(_fs.readdirSync(path), dir => fileSystemEntryExists(combinePaths(path, dir), FileSystemEntryKind.Directory));
 }
開發者ID:8Observer8,項目名稱:TypeScript,代碼行數:3,代碼來源:sys.ts

示例7: readdirSync

 const getDirectories = (source: any) =>
   readdirSync(source).map(name => join(source, name)).filter(isDirectory);
開發者ID:vyakymenko,項目名稱:qlikview-extensions-starter-pack-es6,代碼行數:2,代碼來源:ts.build.prod.ts

示例8: readdirSync

 .then(() => {
   const main = readdirSync('./dist').find(name => !!name.match(/main.[a-z0-9]+\.bundle\.js/));
   expectFileToMatch(`dist/${main}`, /bootstrapModuleFactory\(/);
 })
開發者ID:chiholiu,項目名稱:tcl-angular,代碼行數:4,代碼來源:prod-build.ts

示例9:

					return service.copyFile(source.resource, target, true).then(res => { // CONWAY.js => conway.js
						assert.equal(fs.existsSync(res.resource.fsPath), true);
						assert.ok(fs.readdirSync(testDir).some(f => f === 'conway.js'));
					});
開發者ID:liunian,項目名稱:vscode,代碼行數:4,代碼來源:fileService.test.ts

示例10: readFilesOrURLsInDirectory

    async function readFilesOrURLsInDirectory(d: string): Promise<TypeSource[]> {
        const files = fs
            .readdirSync(d)
            .map(x => path.join(d, x))
            .filter(x => fs.lstatSync(x).isFile());
        // Each file is a (Name, JSON | URL)
        const sourcesInDir: TypeSource[] = [];
        const graphQLSources: GraphQLTypeSource[] = [];
        let graphQLSchema: Readable | undefined = undefined;
        let graphQLSchemaFileName: string | undefined = undefined;
        for (let file of files) {
            const name = typeNameFromFilename(file);

            let fileOrUrl = file;
            file = file.toLowerCase();

            // If file is a URL string, download it
            if (file.endsWith(".url")) {
                fileOrUrl = fs.readFileSync(file, "utf8").trim();
            }

            if (file.endsWith(".url") || file.endsWith(".json")) {
                sourcesInDir.push({
                    kind: "json",
                    name,
                    samples: [await readableFromFileOrURL(fileOrUrl)]
                });
            } else if (file.endsWith(".schema")) {
                sourcesInDir.push({
                    kind: "schema",
                    name,
                    uris: [fileOrUrl]
                });
            } else if (file.endsWith(".gqlschema")) {
                messageAssert(graphQLSchema === undefined, "DriverMoreThanOneGraphQLSchemaInDir", {
                    dir: dataDir
                });
                graphQLSchema = await readableFromFileOrURL(fileOrUrl);
                graphQLSchemaFileName = fileOrUrl;
            } else if (file.endsWith(".graphql")) {
                graphQLSources.push({
                    kind: "graphql",
                    name,
                    schema: undefined,
                    query: await getStream(await readableFromFileOrURL(fileOrUrl))
                });
            }
        }

        if (graphQLSources.length > 0) {
            if (graphQLSchema === undefined) {
                return messageError("DriverNoGraphQLSchemaInDir", { dir: dataDir });
            }
            const schema = parseJSON(await getStream(graphQLSchema), "GraphQL schema", graphQLSchemaFileName);
            for (const source of graphQLSources) {
                source.schema = schema;
                sourcesInDir.push(source);
            }
        }

        return sourcesInDir;
    }
開發者ID:nrkn,項目名稱:quicktype,代碼行數:62,代碼來源:index.ts

示例11: ExportToCsv

import * as fs from 'fs'
import { ExportToCsv } from 'export-to-csv'

const gamesDir = process.argv[2]
const csvFilename = `${gamesDir}/games.csv`
const csvExporter = new ExportToCsv({
  fieldSeparator: ',',
  quoteStrings: '"',
  showLabels: true,
  useKeysAsHeaders: true,
});

const lineRegex = /\[([^"]+) "(.+)"\]/
const allGameData = []
fs.readdirSync(gamesDir).sort().forEach(filename => {
  const lines = fs.readFileSync(`${gamesDir}/${filename}`).toString().split('\n')
  const gameData = {}
  lines.forEach(line => {
    if (line.startsWith('1.')) {
      gameData['Moves'] = line.replace(/\r$/, '')
    } else {
      const match = line.match(lineRegex)
      if (match) {
        const [name, value] = match.slice(1, 3)
        gameData[name] = value
      }
    }
  })
  allGameData.push(gameData)
})
const csvData = csvExporter.generateCsv(allGameData, true)
開發者ID:srfarley,項目名稱:pente-graph,代碼行數:31,代碼來源:games2csv.ts

示例12: samplesFromDirectory

async function samplesFromDirectory(dataDir: string): Promise<TypeSource[]> {
    async function readFilesOrURLsInDirectory(d: string): Promise<TypeSource[]> {
        const files = fs
            .readdirSync(d)
            .map(x => path.join(d, x))
            .filter(x => fs.lstatSync(x).isFile());
        // Each file is a (Name, JSON | URL)
        const sourcesInDir: TypeSource[] = [];
        const graphQLSources: GraphQLTypeSource[] = [];
        let graphQLSchema: Readable | undefined = undefined;
        let graphQLSchemaFileName: string | undefined = undefined;
        for (let file of files) {
            const name = typeNameFromFilename(file);

            let fileOrUrl = file;
            file = file.toLowerCase();

            // If file is a URL string, download it
            if (file.endsWith(".url")) {
                fileOrUrl = fs.readFileSync(file, "utf8").trim();
            }

            if (file.endsWith(".url") || file.endsWith(".json")) {
                sourcesInDir.push({
                    kind: "json",
                    name,
                    samples: [await readableFromFileOrURL(fileOrUrl)]
                });
            } else if (file.endsWith(".schema")) {
                sourcesInDir.push({
                    kind: "schema",
                    name,
                    uris: [fileOrUrl]
                });
            } else if (file.endsWith(".gqlschema")) {
                messageAssert(graphQLSchema === undefined, "DriverMoreThanOneGraphQLSchemaInDir", {
                    dir: dataDir
                });
                graphQLSchema = await readableFromFileOrURL(fileOrUrl);
                graphQLSchemaFileName = fileOrUrl;
            } else if (file.endsWith(".graphql")) {
                graphQLSources.push({
                    kind: "graphql",
                    name,
                    schema: undefined,
                    query: await getStream(await readableFromFileOrURL(fileOrUrl))
                });
            }
        }

        if (graphQLSources.length > 0) {
            if (graphQLSchema === undefined) {
                return messageError("DriverNoGraphQLSchemaInDir", { dir: dataDir });
            }
            const schema = parseJSON(await getStream(graphQLSchema), "GraphQL schema", graphQLSchemaFileName);
            for (const source of graphQLSources) {
                source.schema = schema;
                sourcesInDir.push(source);
            }
        }

        return sourcesInDir;
    }

    const contents = fs.readdirSync(dataDir).map(x => path.join(dataDir, x));
    const directories = contents.filter(x => fs.lstatSync(x).isDirectory());

    let sources = await readFilesOrURLsInDirectory(dataDir);

    for (const dir of directories) {
        let jsonSamples: Readable[] = [];
        const schemaSources: SchemaTypeSource[] = [];
        const graphQLSources: GraphQLTypeSource[] = [];

        for (const source of await readFilesOrURLsInDirectory(dir)) {
            switch (source.kind) {
                case "json":
                    jsonSamples = jsonSamples.concat(source.samples);
                    break;
                case "schema":
                    schemaSources.push(source);
                    break;
                case "graphql":
                    graphQLSources.push(source);
                    break;
                default:
                    return assertNever(source);
            }
        }

        if (jsonSamples.length > 0 && schemaSources.length + graphQLSources.length > 0) {
            return messageError("DriverCannotMixJSONWithOtherSamples", { dir: dir });
        }

        const oneUnlessEmpty = (xs: any[]) => Math.sign(xs.length);
        if (oneUnlessEmpty(schemaSources) + oneUnlessEmpty(graphQLSources) > 1) {
            return messageError("DriverCannotMixNonJSONInputs", { dir: dir });
        }

        if (jsonSamples.length > 0) {
//.........這裏部分代碼省略.........
開發者ID:nrkn,項目名稱:quicktype,代碼行數:101,代碼來源:index.ts

示例13: return

#!/usr/bin/env node

import * as fs from 'fs';
import * as path from 'path';

import Tunnel from '../Tunnel';

const digdugPath = path.dirname(__dirname);

const tunnels = fs
  .readdirSync(digdugPath)
  .filter(function(name) {
    return (
      /[A-Z]\w+Tunnel\.js$/.test(name) &&
      name !== 'NullTunnel.js' &&
      name !== 'Tunnel.js' &&
      name !== 'SeleniumTunnel.js'
    );
  })
  .map(function(name) {
    return name.slice(0, name.length - 3);
  });

if (process.argv.length !== 3) {
  console.log('usage: environments TUNNEL');
  console.log();
  console.log('Available tunnels:');
  tunnels.forEach(function(tunnel) {
    console.log('  ' + tunnel);
  });
  process.exit(1);
開發者ID:theintern,項目名稱:digdug,代碼行數:31,代碼來源:digdugEnvironments.ts

示例14: scanDirectory

 /**
  * scanDirectory
  * 
  * @params directoryPath : string
  * @return directoryFileNames : Array<string>
  */
 private scanDirectory(directoryPath : string) : Array<string> {
     return FileSystem.readdirSync(directoryPath);
 }
開發者ID:Gog0,項目名稱:NodeCrawler,代碼行數:9,代碼來源:PropertyFileScanner.ts

示例15: ensureAppdataDirExists

fr.winKillProcessOnExit();
ensureAppdataDirExists();

const trainedModelFile = 'faceRecognition2Model_150.json';
const trainedModelFilePath = path.resolve(getAppdataPath(), trainedModelFile);

const dataPath = path.resolve('../../data');
const facesPath = path.resolve(dataPath, 'faces');
const classNames = ['sheldon', 'lennard', 'raj', 'howard', 'stuart'];

const detector = fr.FaceDetector();
const recognizer = fr.FaceRecognizer();

if (!fs.existsSync(trainedModelFilePath)) {
    console.log('%s not found, start training recognizer...', trainedModelFile);
    const allFiles = fs.readdirSync(facesPath);
    const imagesByClass = classNames.map((c) =>
        allFiles
            .filter((f) => f.includes(c))
            .map((f) => path.join(facesPath, f))
            .map((fp) => fr.loadImage(fp))
    );

    imagesByClass.forEach((faces, label) =>
        recognizer.addFaces(faces, classNames[label]));

    fs.writeFileSync(trainedModelFilePath, JSON.stringify(recognizer.serialize()));
} else {
    console.log('found %s, loading model', trainedModelFile);

    // tslint:disable-next-line:no-var-requires
開發者ID:Ogeh-Ezeonu,項目名稱:face-recognition.js,代碼行數:31,代碼來源:faceRecognition2.ts


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