• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

TypeScript fs.readdirSync函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了TypeScript中fs.readdirSync函数的典型用法代码示例。如果您正苦于以下问题:TypeScript readdirSync函数的具体用法?TypeScript readdirSync怎么用?TypeScript readdirSync使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了readdirSync函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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


示例16: function

engineio.attach(http);
//var engineio = engine.attach(http);
//console.log(engineio);
app.get('/engine.io.js', function(req, res) {
  res.sendFile(path.join(__dirname + '/node_modules/engine.io-client/engine.io.js'));
});

if(__dirname == null){
	__dirname = "./";
}

//var routes = express.Router(); //Router is for page access

//load initalizers
//console.log("loading Sync initalizers:");
var init_files = fs.readdirSync(__dirname + "/app/initalizers");
init_files.forEach(function(initFile){
	if(path.extname(initFile) == '.js'){//check if javascript ext. file
		console.log('loading initalizer: ' + initFile);
		require(__dirname + "/app/initalizers/" + initFile);
	}
});

//load models
//console.log("loading Sync models:");
var model_files = fs.readdirSync(__dirname + "/app/models");
model_files.forEach(function(modelFile){
	if(path.extname(modelFile) == '.js'){//check if javascript ext. file
		console.log('loading model: ' + modelFile);
		require(__dirname + "/app/models/" + modelFile);
	}
开发者ID:Lightnet,项目名称:pcrpgow-ns,代码行数:31,代码来源:server_express.ts


示例17: getDirectoriesToWatch

function getDirectoriesToWatch(workingDir: string) {
  readdirSync(workingDir).
    filter(onlyDirectory).
    forEach(insertFileToWatchList);
}
开发者ID:rupeshtiwari,项目名称:chutzpah-watch,代码行数:5,代码来源:watch-testfiles.ts


示例18: getSubdirectoryNames

export function getSubdirectoryNames(dir: string): string[] {
  return readdirSync(dir).filter(f => lstatSync(join(dir, f)).isDirectory());
}
开发者ID:GuzmanPI,项目名称:material2,代码行数:3,代码来源:secondary-entry-points.ts


示例19: require

import fr = require('../../../');
import { getAppdataPath, ensureAppdataDirExists } from './commons';

fr.winKillProcessOnExit();
ensureAppdataDirExists();

const numTrainFaces = 5;
const trainedModelFile = `faceRecognition1Model_t${numTrainFaces}_150.json`;
const trainedModelFilePath = path.resolve(getAppdataPath(), trainedModelFile);

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

const recognizer = fr.AsyncFaceRecognizer();

const allFiles = fs.readdirSync(dataPath);
const imagesByClass = classNames.map((c) =>
    allFiles
        .filter((f) => f.includes(c))
        .map((f) => path.join(dataPath, f))
        .map((fp) => fr.loadImage(fp))
);

const trainDataByClass = imagesByClass.map((imgs) => imgs.slice(0, numTrainFaces));
const testDataByClass = imagesByClass.map((imgs) => imgs.slice(numTrainFaces));

function runClassification() {
    const errors = classNames.map((_) => 0);
    Promise.all(
        testDataByClass.map(
            (faces, label) =>
开发者ID:Ogeh-Ezeonu,项目名称:face-recognition.js,代码行数:31,代码来源:asyncFaceRecognition.ts


示例20: everyRule

function everyRule(): string[] {
    return fs.readdirSync(srcRulesDir)
        .filter((file) => /Rule.ts$/.test(file))
        .map((file) => file.substr(0, file.length - "Rule.ts".length))
        .sort();
}
开发者ID:IllusionMH,项目名称:tslint,代码行数:6,代码来源:ruleLoaderTests.ts



注:本文中的fs.readdirSync函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript fs.readlink函数代码示例发布时间:2022-05-25
下一篇:
TypeScript fs.readdir函数代码示例发布时间:2022-05-25
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap