You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中如何同步获取CSV文件首行(不使用Promise)

Node.js同步获取文件首行实现方案

直接用Node.js内置的fs模块同步读取方法就能实现,以下是完整的get_firstline函数实现:

const fs = require('fs');
const filename = 'test.csv'

const get_firstline = () => {
    // 同步读取文件内容,指定utf8编码避免返回Buffer格式
    const fileContent = fs.readFileSync(filename, 'utf8');
    // 按换行符分割内容,兼容Windows(\r\n)和Unix(\n)系统的换行格式
    const lines = fileContent.split(/\r?\n/);
    // 返回第一行,空文件场景下返回空字符串避免undefined
    return lines[0] || '';
}

const process_firstline = (firstline) => {
    console.log(firstline)
}

process_firstline(get_firstline())

关键点说明

  • 必须先引入fs模块,这是Node.js处理文件操作的核心内置模块
  • readFileSync是同步读取方法,会阻塞后续代码直到文件读取完成,适合小文件场景使用
  • 正则/\r?\n/能同时匹配两种主流换行格式,避免因系统差异导致的分割错误
  • 加入|| ''是为了兼容空文件的极端情况,保证函数始终返回字符串类型

内容的提问来源于stack exchange,提问作者0x4141

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 18:18:07